import { useState, useEffect } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { formatBytes } from '@/lib/format'
import { zfsApi, snapshotApi, snapshotScheduleApi, replicationApi, type Snapshot, type CreateSnapshotRequest, type SnapshotSchedule, type CreateSnapshotScheduleRequest, type ReplicationTask, type CreateReplicationTaskRequest } from '@/api/storage'
import {
  Camera,
  History,
  Plus,
  Search,
  Calendar,
  RotateCcw,
  Copy,
  Trash2,
  RefreshCw,
  Clock,
  TrendingUp,
  CloudSync,
  AlertCircle,
  MoreVertical,
  X,
  Save,
  Edit
} from 'lucide-react'
import { Link } from 'react-router-dom'
import { ChevronRight } from 'lucide-react'
import { Button } from '@/components/ui/button'


export default function SnapshotReplication() {
  const [activeTab, setActiveTab] = useState<'snapshots' | 'schedules' | 'replication' | 'restore'>('snapshots')
  const [searchQuery, setSearchQuery] = useState('')
  const [currentPage, setCurrentPage] = useState(1)
  const [showCreateReplication, setShowCreateReplication] = useState(false)
  const [showCreateSnapshot, setShowCreateSnapshot] = useState(false)
  const [showCreateSchedule, setShowCreateSchedule] = useState(false)
  const [editingSchedule, setEditingSchedule] = useState<SnapshotSchedule | null>(null)
  const [snapshotForm, setSnapshotForm] = useState({
    dataset: '',
    name: '',
    recursive: false,
  })
  const [scheduleForm, setScheduleForm] = useState<CreateSnapshotScheduleRequest>({
    name: '',
    dataset: '',
    snapshot_name_template: 'auto-%Y-%m-%d-%H%M',
    schedule_type: 'daily',
    schedule_config: { time: '00:00' },
    recursive: false,
  })
  const [selectedDatasetFilter, setSelectedDatasetFilter] = useState<string>('')
  const [deleteConfirmSnapshot, setDeleteConfirmSnapshot] = useState<string | null>(null)
  const [rollbackConfirmSnapshot, setRollbackConfirmSnapshot] = useState<string | null>(null)
  const itemsPerPage = 10
  const queryClient = useQueryClient()

  // Form state for replication
  const [replicationForm, setReplicationForm] = useState<CreateReplicationTaskRequest>({
    name: '',
    direction: 'outbound',
    source_dataset: '',
    target_host: '',
    target_port: 22,
    target_user: 'root',
    target_dataset: '',
    source_host: '',
    source_port: 22,
    source_user: 'root',
    local_dataset: '',
    schedule_type: 'daily',
    schedule_config: { time: '00:00' },
    compression: 'lz4',
    recursive: false,
    incremental: true,
    auto_snapshot: true,
    encryption: false,
    enabled: true,
  })
  const [editingReplication, setEditingReplication] = useState<ReplicationTask | null>(null)

  // Fetch pools and datasets for form
  const { data: pools = [] } = useQuery({
    queryKey: ['replication-pools'],
    queryFn: zfsApi.listPools,
  })

  // Fetch snapshots from API
  const { data: snapshots = [], isLoading: snapshotsLoading, refetch: refetchSnapshots } = useQuery<Snapshot[]>({
    queryKey: ['snapshots', selectedDatasetFilter],
    queryFn: () => snapshotApi.listSnapshots(selectedDatasetFilter || undefined),
    refetchInterval: 5000, // Auto-refresh every 5 seconds
    staleTime: 0,
  })

  // Fetch snapshot schedules
  const { data: schedules = [], isLoading: schedulesLoading, refetch: refetchSchedules } = useQuery<SnapshotSchedule[]>({
    queryKey: ['snapshot-schedules'],
    queryFn: snapshotScheduleApi.listSchedules,
    refetchInterval: 5000,
    staleTime: 0,
  })

  // Fetch replication tasks
  const { data: allReplicationTasks = [], isLoading: replicationLoading, refetch: refetchReplications } = useQuery<ReplicationTask[]>({
    queryKey: ['replication-tasks'],
    queryFn: () => replicationApi.listTasks(),
    refetchInterval: 5000,
    staleTime: 0,
  })

  // Separate outbound and inbound replication tasks
  const outboundTasks = allReplicationTasks.filter(task => task.direction === 'outbound')
  const inboundTasks = allReplicationTasks.filter(task => task.direction === 'inbound')

  const [datasets, setDatasets] = useState<Array<{ pool: string; datasets: any[] }>>([])

  // Fetch datasets for selected pool
  const fetchDatasets = async (poolName: string) => {
    try {
      const pool = pools.find(p => p.name === poolName || p.id === poolName)
      if (!pool) return
      
      // Check if datasets already loaded for this pool
      const existing = datasets.find(d => d.pool === poolName || d.pool === pool.id || d.pool === pool.name)
      if (existing) return
      
      const poolDatasets = await zfsApi.listDatasets(pool.id)
      setDatasets((prev) => {
        const filtered = prev.filter((d) => d.pool !== poolName && d.pool !== pool.id && d.pool !== pool.name)
        return [...filtered, { pool: pool.name, datasets: poolDatasets }]
      })
    } catch (error) {
      console.error('Failed to fetch datasets:', error)
    }
  }

  // Fetch datasets for all pools when modal opens
  const fetchAllDatasets = async () => {
    if (pools.length === 0) return
    
    for (const pool of pools) {
      try {
        // Check if already loaded
        const existing = datasets.find(d => d.pool === pool.name || d.pool === pool.id)
        if (existing) continue
        
        const poolDatasets = await zfsApi.listDatasets(pool.id)
        setDatasets((prev) => {
          const filtered = prev.filter((d) => d.pool !== pool.name && d.pool !== pool.id)
          return [...filtered, { pool: pool.name, datasets: poolDatasets }]
        })
      } catch (error) {
        console.error(`Failed to fetch datasets for pool ${pool.name}:`, error)
      }
    }
  }

  // Fetch datasets when modal opens
  useEffect(() => {
    if (showCreateSnapshot && pools.length > 0) {
      fetchAllDatasets()
    }
  }, [showCreateSnapshot, pools.length])

  // Load datasets when schedule modal opens
  useEffect(() => {
    if (showCreateSchedule && pools.length > 0) {
      fetchAllDatasets()
    }
  }, [showCreateSchedule, pools.length])

  // Populate form when editing schedule
  useEffect(() => {
    if (editingSchedule) {
      setScheduleForm({
        name: editingSchedule.name,
        dataset: editingSchedule.dataset,
        snapshot_name_template: editingSchedule.snapshot_name_template,
        schedule_type: editingSchedule.schedule_type,
        schedule_config: editingSchedule.schedule_config,
        recursive: editingSchedule.recursive,
        retention_count: editingSchedule.retention_count,
        retention_days: editingSchedule.retention_days,
      })
    } else if (!showCreateSchedule) {
      // Reset form when modal closes
      setScheduleForm({
        name: '',
        dataset: '',
        snapshot_name_template: 'auto-%Y-%m-%d-%H%M',
        schedule_type: 'daily',
        schedule_config: { time: '00:00' },
        recursive: false,
      })
    }
  }, [editingSchedule, showCreateSchedule])

  // Create snapshot mutation
  const createSnapshotMutation = useMutation({
    mutationFn: (data: CreateSnapshotRequest) => snapshotApi.createSnapshot(data),
    onSuccess: async () => {
      // Close modal first
      setShowCreateSnapshot(false)
      setSnapshotForm({ dataset: '', name: '', recursive: false })
      
      // Invalidate and refetch snapshots immediately
      await queryClient.invalidateQueries({ queryKey: ['snapshots'] })
      await refetchSnapshots()
      
      alert('Snapshot created successfully!')
    },
    onError: (error: any) => {
      alert(error.response?.data?.error || 'Failed to create snapshot')
    },
  })

  // Delete snapshot mutation
  const deleteSnapshotMutation = useMutation({
    mutationFn: ({ name, recursive }: { name: string; recursive?: boolean }) => 
      snapshotApi.deleteSnapshot(name, recursive),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['snapshots'] })
      setDeleteConfirmSnapshot(null)
      alert('Snapshot deleted successfully!')
    },
    onError: (error: any) => {
      alert(error.response?.data?.error || 'Failed to delete snapshot')
    },
  })

  // Rollback snapshot mutation
  const rollbackSnapshotMutation = useMutation({
    mutationFn: ({ name, force }: { name: string; force?: boolean }) => 
      snapshotApi.rollbackSnapshot(name, force),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['snapshots'] })
      setRollbackConfirmSnapshot(null)
      alert('Snapshot rollback completed successfully!')
    },
    onError: (error: any) => {
      alert(error.response?.data?.error || 'Failed to rollback snapshot')
    },
  })

  // Filter snapshots
  const filteredSnapshots = snapshots.filter((snapshot) => {
    const matchesSearch =
      snapshot.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      snapshot.dataset.toLowerCase().includes(searchQuery.toLowerCase()) ||
      snapshot.snapshot_name.toLowerCase().includes(searchQuery.toLowerCase())
    return matchesSearch
  })

  // Pagination
  const totalPages = Math.ceil(filteredSnapshots.length / itemsPerPage)
  const paginatedSnapshots = filteredSnapshots.slice(
    (currentPage - 1) * itemsPerPage,
    currentPage * itemsPerPage
  )

  // Calculate totals
  const totalSnapshots = snapshots.length
  const totalReclaimable = snapshots.reduce((sum, s) => sum + s.referenced, 0)

  // Format date
  const formatDate = (dateString: string) => {
    const date = new Date(dateString)
    return date.toLocaleDateString('en-US', {
      month: 'short',
      day: 'numeric',
      year: 'numeric',
      hour: 'numeric',
      minute: '2-digit',
    })
  }

  return (
    <div className="flex-1 overflow-hidden flex flex-col bg-background-dark">
      {/* Header */}
      <header className="flex items-center justify-between px-8 py-5 border-b border-[#233648] bg-background-dark shrink-0">
        <div className="flex items-center gap-2">
          <Link to="/storage" className="text-text-secondary hover:text-white text-sm font-medium transition-colors">
            Storage
          </Link>
          <ChevronRight className="text-[#536b85]" size={16} />
          <Link to="/storage" className="text-text-secondary hover:text-white text-sm font-medium transition-colors">
            Pools
          </Link>
          <ChevronRight className="text-[#536b85]" size={16} />
          <span className="text-white text-sm font-bold bg-[#1e2936] px-2 py-1 rounded">Data Protection</span>
        </div>
        <div className="flex items-center gap-4">
          <button className="flex items-center justify-center w-8 h-8 rounded-full hover:bg-[#1e2936] text-text-secondary transition-colors relative">
            <AlertCircle size={20} />
            <span className="absolute top-1.5 right-1.5 w-2 h-2 bg-red-500 rounded-full border border-background-dark"></span>
          </button>
          <button className="flex items-center justify-center w-8 h-8 rounded-full hover:bg-[#1e2936] text-text-secondary transition-colors">
            <MoreVertical size={20} />
          </button>
        </div>
      </header>

      {/* Scrollable Page Content */}
      <div className="flex-1 overflow-y-auto p-8 custom-scrollbar">
        <div className="mx-auto max-w-[1200px] flex flex-col gap-8">
          {/* Page Heading */}
          <div className="flex flex-col md:flex-row md:items-end justify-between gap-4">
            <div className="flex flex-col gap-2">
              <h1 className="text-white text-3xl font-extrabold tracking-tight">Snapshots & Replication</h1>
              <p className="text-text-secondary text-base font-normal max-w-2xl">
                Manage local ZFS snapshots and configure remote replication tasks to ensure data redundancy and disaster recovery.
              </p>
            </div>
            <div className="flex gap-3">
              <button className="px-4 py-2 bg-[#1e2936] hover:bg-[#2a3b4d] text-white text-sm font-bold rounded-lg border border-[#324d67] transition-all flex items-center gap-2">
                <History size={18} />
                View Logs
              </button>
              <button
                onClick={() => {
                  if (activeTab === 'replication') {
                    setShowCreateReplication(true)
                  } else if (activeTab === 'schedules') {
                    setEditingSchedule(null)
                    setShowCreateSchedule(true)
                  } else {
                    setShowCreateSnapshot(true)
                  }
                }}
                className="px-4 py-2 bg-primary hover:bg-blue-600 text-white text-sm font-bold rounded-lg shadow-[0_4px_12px_rgba(19,127,236,0.3)] transition-all flex items-center gap-2"
              >
                <Plus size={18} />
                {activeTab === 'replication' 
                  ? 'Create Replication' 
                  : activeTab === 'schedules' 
                  ? 'Create Schedule' 
                  : 'Create Snapshot'}
              </button>
            </div>
          </div>

          {/* Stats Cards */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            {/* Total Snapshots */}
            <div className="flex flex-col gap-1 rounded-xl p-5 bg-[#18232e] border border-[#2a3b4d] relative overflow-hidden group">
              <div className="absolute top-0 right-0 p-4 opacity-10 group-hover:opacity-20 transition-opacity">
                <Camera className="text-6xl text-primary" />
              </div>
              <p className="text-text-secondary text-sm font-medium uppercase tracking-wider">Total Snapshots</p>
              <div className="flex items-end gap-2">
                <p className="text-white text-3xl font-bold tracking-tight">{totalSnapshots.toLocaleString()}</p>
                <span className="text-emerald-400 text-sm font-medium mb-1 flex items-center">
                  <TrendingUp size={14} className="mr-0.5" />
                  +12 today
                </span>
              </div>
              <p className="text-[#536b85] text-xs font-medium mt-1">{formatBytes(totalReclaimable, 1)} Reclaimable Space</p>
            </div>

            {/* Last Replication */}
            <div className="flex flex-col gap-1 rounded-xl p-5 bg-[#18232e] border border-[#2a3b4d] relative overflow-hidden group">
              <div className="absolute top-0 right-0 p-4 opacity-10 group-hover:opacity-20 transition-opacity">
                <RefreshCw className="text-6xl text-emerald-500" />
              </div>
              <p className="text-text-secondary text-sm font-medium uppercase tracking-wider">Last Replication</p>
              <div className="flex items-end gap-2">
                <p className="text-white text-3xl font-bold tracking-tight">Success</p>
              </div>
              <p className="text-[#536b85] text-xs font-medium mt-1">15 mins ago • tank/backup</p>
            </div>

            {/* Next Scheduled */}
            <div className="flex flex-col gap-1 rounded-xl p-5 bg-[#18232e] border border-[#2a3b4d] relative overflow-hidden group">
              <div className="absolute top-0 right-0 p-4 opacity-10 group-hover:opacity-20 transition-opacity">
                <Clock className="text-6xl text-purple-500" />
              </div>
              <p className="text-text-secondary text-sm font-medium uppercase tracking-wider">Next Scheduled</p>
              <div className="flex items-end gap-2">
                <p className="text-white text-3xl font-bold tracking-tight">10:00 PM</p>
              </div>
              <p className="text-[#536b85] text-xs font-medium mt-1">Daily Offsite Backup</p>
            </div>
          </div>

          {/* Main Section */}
          <div className="flex flex-col bg-[#18232e] border border-[#2a3b4d] rounded-xl overflow-hidden shadow-sm">
            {/* Tabs Header */}
            <div className="flex border-b border-[#2a3b4d] bg-[#151f29]">
              <button
                onClick={() => setActiveTab('snapshots')}
                className={`px-6 py-4 text-sm font-bold flex items-center gap-2 transition-colors ${
                  activeTab === 'snapshots'
                    ? 'text-white border-b-2 border-primary bg-[#18232e]'
                    : 'text-text-secondary hover:text-white border-b-2 border-transparent hover:bg-[#18232e]'
                }`}
              >
                <Camera size={20} />
                Snapshots
              </button>
              <button
                onClick={() => setActiveTab('schedules')}
                className={`px-6 py-4 text-sm font-bold flex items-center gap-2 transition-colors ${
                  activeTab === 'schedules'
                    ? 'text-white border-b-2 border-primary bg-[#18232e]'
                    : 'text-text-secondary hover:text-white border-b-2 border-transparent hover:bg-[#18232e]'
                }`}
              >
                <Clock size={20} />
                Schedules
                {schedules.length > 0 && (
                  <span className="ml-1 bg-[#2a3b4d] text-white text-[10px] px-1.5 py-0.5 rounded-full">
                    {schedules.length}
                  </span>
                )}
              </button>
              <button
                onClick={() => setActiveTab('replication')}
                className={`px-6 py-4 text-sm font-bold flex items-center gap-2 transition-colors ${
                  activeTab === 'replication'
                    ? 'text-white border-b-2 border-primary bg-[#18232e]'
                    : 'text-text-secondary hover:text-white border-b-2 border-transparent hover:bg-[#18232e]'
                }`}
              >
                <CloudSync size={20} />
                Replication Tasks
                {allReplicationTasks.length > 0 && (
                  <span className="ml-1 bg-[#2a3b4d] text-white text-[10px] px-1.5 py-0.5 rounded-full">
                    {allReplicationTasks.length}
                  </span>
                )}
              </button>
              <button
                onClick={() => setActiveTab('restore')}
                className={`px-6 py-4 text-sm font-bold flex items-center gap-2 transition-colors ${
                  activeTab === 'restore'
                    ? 'text-white border-b-2 border-primary bg-[#18232e]'
                    : 'text-text-secondary hover:text-white border-b-2 border-transparent hover:bg-[#18232e]'
                }`}
              >
                <RotateCcw size={20} />
                Restore Points
              </button>
            </div>

            {/* Toolbar */}
            <div className="p-4 flex flex-col sm:flex-row gap-4 justify-between items-center border-b border-[#2a3b4d] bg-[#18232e]">
              <div className="relative w-full sm:w-96 group">
                <Search className="absolute left-3 top-2.5 text-[#536b85] group-focus-within:text-primary transition-colors" size={20} />
                <input
                  className="w-full bg-[#111a22] border border-[#2a3b4d] text-white text-sm rounded-lg pl-10 pr-4 py-2.5 focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary transition-all placeholder-[#536b85]"
                  placeholder="Search snapshot name or dataset..."
                  type="text"
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                />
              </div>
              <div className="flex gap-3 w-full sm:w-auto">
                <div className="relative group">
                  <select
                    className="flex items-center gap-2 px-4 py-2.5 bg-[#111a22] border border-[#2a3b4d] rounded-lg text-sm font-medium text-text-secondary hover:text-white hover:border-[#536b85] transition-all appearance-none cursor-pointer"
                    value={selectedDatasetFilter}
                    onChange={(e) => {
                      setSelectedDatasetFilter(e.target.value)
                      setCurrentPage(1)
                    }}
                  >
                    <option value="">Dataset: All</option>
                    {Array.from(new Set(snapshots.map(s => s.dataset))).map(dataset => (
                      <option key={dataset} value={dataset}>{dataset}</option>
                    ))}
                  </select>
                </div>
                <div className="relative group">
                  <button className="flex items-center gap-2 px-4 py-2.5 bg-[#111a22] border border-[#2a3b4d] rounded-lg text-sm font-medium text-text-secondary hover:text-white hover:border-[#536b85] transition-all">
                    <Calendar size={18} />
                    Date Range
                  </button>
                </div>
              </div>
            </div>

            {/* Tab Content */}
            {activeTab === 'snapshots' && (
              <>
                {/* Data Table */}
                <div className="overflow-x-auto">
                  <table className="w-full text-left border-collapse">
                    <thead className="bg-[#151f29] text-text-secondary">
                      <tr>
                        <th className="p-4 border-b border-[#2a3b4d] w-[50px]">
                          <input
                            className="w-4 h-4 rounded border-[#324d67] bg-[#111a22] text-primary focus:ring-offset-[#111a22]"
                            type="checkbox"
                          />
                        </th>
                        <th className="p-4 border-b border-[#2a3b4d] text-xs font-bold uppercase tracking-wider">
                          Snapshot Name
                        </th>
                        <th className="p-4 border-b border-[#2a3b4d] text-xs font-bold uppercase tracking-wider">Dataset</th>
                        <th className="p-4 border-b border-[#2a3b4d] text-xs font-bold uppercase tracking-wider">Created</th>
                        <th className="p-4 border-b border-[#2a3b4d] text-xs font-bold uppercase tracking-wider">Referenced</th>
                        <th className="p-4 border-b border-[#2a3b4d] text-xs font-bold uppercase tracking-wider text-right">
                          Actions
                        </th>
                      </tr>
                    </thead>
                    <tbody className="text-sm">
                      {snapshotsLoading ? (
                        <tr>
                          <td colSpan={6} className="p-8 text-center text-text-secondary">
                            Loading snapshots...
                          </td>
                        </tr>
                      ) : paginatedSnapshots.length === 0 ? (
                        <tr>
                          <td colSpan={6} className="p-8 text-center text-text-secondary">
                            {searchQuery ? 'No snapshots found matching your search.' : 'No snapshots yet. Create your first snapshot to get started.'}
                          </td>
                        </tr>
                      ) : (
                        paginatedSnapshots.map((snapshot) => (
                          <tr key={snapshot.id} className="group hover:bg-[#1e2936] transition-colors border-b border-[#2a3b4d]">
                            <td className="p-4">
                              <input
                                className="w-4 h-4 rounded border-[#324d67] bg-[#111a22] text-primary focus:ring-offset-[#111a22]"
                                type="checkbox"
                              />
                            </td>
                            <td className="p-4">
                              <div className="flex items-center gap-2">
                                <Camera className="text-[#536b85]" size={20} />
                                <span className="text-white font-medium">{snapshot.snapshot_name}</span>
                                {snapshot.is_latest && (
                                  <span className="px-2 py-0.5 rounded text-[10px] font-bold bg-primary/20 text-primary border border-primary/20">
                                    LATEST
                                  </span>
                                )}
                              </div>
                            </td>
                            <td className="p-4">
                              <span className="text-text-secondary">{snapshot.dataset}</span>
                            </td>
                            <td className="p-4">
                              <span className="text-text-secondary">{formatDate(snapshot.created)}</span>
                            </td>
                            <td className="p-4">
                              <span className="text-white font-mono">{formatBytes(snapshot.referenced)}</span>
                            </td>
                            <td className="p-4 text-right">
                              <div className="flex items-center justify-end gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
                                <button
                                  onClick={() => setRollbackConfirmSnapshot(snapshot.name)}
                                  className="p-1.5 hover:bg-[#2a3b4d] rounded text-text-secondary hover:text-white"
                                  title="Rollback"
                                >
                                  <RotateCcw size={20} />
                                </button>
                                <button
                                  onClick={() => {
                                    const cloneName = prompt(`Enter clone dataset name for ${snapshot.snapshot_name}:`)
                                    if (cloneName) {
                                      snapshotApi.cloneSnapshot(snapshot.name, { clone_name: cloneName })
                                        .then(() => {
                                          queryClient.invalidateQueries({ queryKey: ['snapshots'] })
                                          alert('Snapshot cloned successfully!')
                                        })
                                        .catch((error: any) => {
                                          alert(error.response?.data?.error || 'Failed to clone snapshot')
                                        })
                                    }
                                  }}
                                  className="p-1.5 hover:bg-[#2a3b4d] rounded text-text-secondary hover:text-white"
                                  title="Clone"
                                >
                                  <Copy size={20} />
                                </button>
                                <button
                                  onClick={() => setDeleteConfirmSnapshot(snapshot.name)}
                                  className="p-1.5 hover:bg-red-500/20 rounded text-text-secondary hover:text-red-500"
                                  title="Delete"
                                >
                                  <Trash2 size={20} />
                                </button>
                              </div>
                            </td>
                          </tr>
                        ))
                      )}
                    </tbody>
                  </table>
                </div>
                {/* Pagination */}
                <div className="flex items-center justify-between p-4 bg-[#18232e]">
                  <p className="text-text-secondary text-sm">
                    Showing <span className="text-white font-bold">1-{paginatedSnapshots.length}</span> of{' '}
                    <span className="text-white font-bold">{filteredSnapshots.length}</span>
                  </p>
                  <div className="flex items-center gap-2">
                    <button
                      onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
                      disabled={currentPage === 1}
                      className="px-3 py-1 text-sm rounded border border-[#2a3b4d] text-text-secondary hover:bg-[#2a3b4d] hover:text-white disabled:opacity-50"
                    >
                      Previous
                    </button>
                    {Array.from({ length: Math.min(3, totalPages) }, (_, i) => i + 1).map((page) => (
                      <button
                        key={page}
                        onClick={() => setCurrentPage(page)}
                        className={`px-3 py-1 text-sm rounded border border-[#2a3b4d] ${
                          currentPage === page
                            ? 'text-white bg-[#2a3b4d]'
                            : 'text-text-secondary hover:bg-[#2a3b4d] hover:text-white'
                        }`}
                      >
                        {page}
                      </button>
                    ))}
                    {totalPages > 3 && <span className="text-text-secondary">...</span>}
                    <button
                      onClick={() => setCurrentPage((p) => Math.min(totalPages, p + 1))}
                      disabled={currentPage === totalPages}
                      className="px-3 py-1 text-sm rounded border border-[#2a3b4d] text-text-secondary hover:bg-[#2a3b4d] hover:text-white disabled:opacity-50"
                    >
                      Next
                    </button>
                  </div>
                </div>
              </>
            )}

            {activeTab === 'schedules' && (
              <div className="p-6">
                <div className="flex justify-between items-center mb-4">
                  <h3 className="text-white text-lg font-bold">Snapshot Schedules</h3>
                  <button
                    onClick={() => {
                      setEditingSchedule(null)
                      setShowCreateSchedule(true)
                    }}
                    className="flex items-center gap-2 px-4 py-2 bg-primary hover:bg-blue-600 text-white text-sm font-bold rounded-lg transition-colors"
                  >
                    <Plus size={18} />
                    Create Schedule
                  </button>
                </div>
                {schedulesLoading ? (
                  <div className="text-center py-8 text-text-secondary">Loading schedules...</div>
                ) : schedules.length === 0 ? (
                  <div className="text-center py-8 text-text-secondary">
                    No schedules configured. Create your first schedule to automate snapshot creation.
                  </div>
                ) : (
                  <div className="space-y-3">
                    {schedules.map((schedule) => (
                      <div
                        key={schedule.id}
                        className="flex items-center gap-4 bg-[#111a22] p-4 rounded-lg border border-[#2a3b4d] hover:bg-[#1e2936] transition-colors"
                      >
                        <div className={`w-2 h-2 rounded-full ${schedule.enabled ? 'bg-emerald-500' : 'bg-gray-500'}`}></div>
                        <div className="flex-1">
                          <div className="flex items-center gap-2">
                            <p className="text-white text-sm font-medium">{schedule.name}</p>
                            <span className="px-2 py-0.5 rounded text-[10px] font-bold bg-[#2a3b4d] text-text-secondary">
                              {schedule.schedule_type}
                            </span>
                          </div>
                          <p className="text-[#536b85] text-xs mt-1">
                            Dataset: {schedule.dataset} • Template: {schedule.snapshot_name_template}
                          </p>
                          {schedule.next_run_at && (
                            <p className="text-[#536b85] text-xs mt-1">
                              Next run: {new Date(schedule.next_run_at).toLocaleString()}
                            </p>
                          )}
                        </div>
                        <div className="flex items-center gap-2">
                          <button
                            onClick={async () => {
                              try {
                                await snapshotScheduleApi.toggleSchedule(schedule.id, !schedule.enabled)
                                await queryClient.invalidateQueries({ queryKey: ['snapshot-schedules'] })
                                await refetchSchedules()
                                alert(`Schedule ${schedule.enabled ? 'disabled' : 'enabled'} successfully`)
                              } catch (error: any) {
                                alert(error.response?.data?.error || 'Failed to toggle schedule')
                              }
                            }}
                            className={`px-3 py-1 text-xs font-medium rounded transition-colors ${
                              schedule.enabled
                                ? 'bg-emerald-500/20 text-emerald-400 hover:bg-emerald-500/30'
                                : 'bg-gray-500/20 text-gray-400 hover:bg-gray-500/30'
                            }`}
                          >
                            {schedule.enabled ? 'Enabled' : 'Disabled'}
                          </button>
                          <button
                            onClick={() => {
                              setEditingSchedule(schedule)
                              setShowCreateSchedule(true)
                            }}
                            className="flex items-center gap-1.5 px-3 py-1.5 hover:bg-[#2a3b4d] rounded text-text-secondary hover:text-white transition-colors border border-[#2a3b4d] hover:border-primary"
                            title="Edit Schedule"
                          >
                            <Edit size={16} />
                            <span className="text-xs font-medium">Edit</span>
                          </button>
                          <button
                            onClick={async () => {
                              if (confirm(`Delete schedule "${schedule.name}"?`)) {
                                try {
                                  await snapshotScheduleApi.deleteSchedule(schedule.id)
                                  await queryClient.invalidateQueries({ queryKey: ['snapshot-schedules'] })
                                  await refetchSchedules()
                                  alert('Schedule deleted successfully')
                                } catch (error: any) {
                                  alert(error.response?.data?.error || 'Failed to delete schedule')
                                }
                              }
                            }}
                            className="p-1.5 hover:bg-red-500/20 rounded text-text-secondary hover:text-red-500 transition-colors"
                            title="Delete Schedule"
                          >
                            <Trash2 size={18} />
                          </button>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            )}

            {activeTab === 'replication' && (
              <div className="p-6 space-y-6">
                <div className="flex justify-between items-center">
                  <h3 className="text-white text-lg font-bold">Replication Tasks</h3>
                  <button
                    onClick={() => {
                      setEditingReplication(null)
                      setReplicationForm({
                        name: '',
                        direction: 'outbound',
                        source_dataset: '',
                        target_host: '',
                        target_port: 22,
                        target_user: 'root',
                        target_dataset: '',
                        source_host: '',
                        source_port: 22,
                        source_user: 'root',
                        local_dataset: '',
                        schedule_type: 'daily',
                        schedule_config: { time: '00:00' },
                        compression: 'lz4',
                        recursive: false,
                        incremental: true,
                        auto_snapshot: true,
                        encryption: false,
                        enabled: true,
                      })
                      setShowCreateReplication(true)
                    }}
                    className="flex items-center gap-2 px-4 py-2 bg-primary hover:bg-blue-600 text-white text-sm font-bold rounded-lg transition-colors"
                  >
                    <Plus size={18} />
                    Create Replication
                  </button>
                </div>

                {/* Outbound Replication Section */}
                <div>
                  <div className="flex items-center gap-2 mb-4">
                    <CloudSync size={20} className="text-primary" />
                    <h4 className="text-white text-base font-bold">Outbound Replication</h4>
                    <span className="text-text-secondary text-sm">(Sending to remote)</span>
                  </div>
                  {replicationLoading ? (
                    <div className="text-center py-8 text-text-secondary">Loading replication tasks...</div>
                  ) : outboundTasks.length === 0 ? (
                    <div className="text-center py-8 text-text-secondary bg-[#111a22] rounded-lg border border-[#2a3b4d]">
                      No outbound replication tasks configured.
                    </div>
                  ) : (
                    <div className="space-y-3">
                      {outboundTasks.map((task) => (
                        <div
                          key={task.id}
                          className="flex items-center gap-4 bg-[#111a22] p-4 rounded-lg border border-[#2a3b4d] hover:bg-[#1e2936] transition-colors"
                        >
                          <div
                            className={`w-2 h-2 rounded-full ${
                              task.status === 'running'
                                ? 'bg-primary animate-pulse'
                                : task.status === 'failed'
                                ? 'bg-red-500'
                                : 'bg-emerald-500'
                            }`}
                          ></div>
                          <div className="flex-1">
                            <div className="flex items-center gap-2">
                              <p className="text-white text-sm font-medium">{task.name}</p>
                              {!task.enabled && (
                                <span className="px-2 py-0.5 rounded text-[10px] font-bold bg-gray-500/20 text-gray-400">
                                  Disabled
                                </span>
                              )}
                            </div>
                            <p className="text-[#536b85] text-xs mt-1">
                              Source: {task.source_dataset} → Target: {task.target_host}:{task.target_port} ({task.target_dataset})
                            </p>
                            {task.last_run_at && (
                              <p className="text-[#536b85] text-xs mt-1">
                                Last run: {new Date(task.last_run_at).toLocaleString()}
                                {task.last_run_status && (
                                  <span className={`ml-2 ${task.last_run_status === 'success' ? 'text-emerald-400' : 'text-red-400'}`}>
                                    ({task.last_run_status})
                                  </span>
                                )}
                              </p>
                            )}
                          </div>
                          <div className="flex items-center gap-2">
                            <button
                              onClick={() => {
                                setEditingReplication(task)
                                setReplicationForm({
                                  name: task.name,
                                  direction: task.direction,
                                  source_dataset: task.source_dataset,
                                  target_host: task.target_host,
                                  target_port: task.target_port,
                                  target_user: task.target_user,
                                  target_dataset: task.target_dataset,
                                  source_host: task.source_host,
                                  source_port: task.source_port,
                                  source_user: task.source_user,
                                  local_dataset: task.local_dataset,
                                  schedule_type: task.schedule_type,
                                  schedule_config: task.schedule_config,
                                  compression: task.compression,
                                  recursive: task.recursive,
                                  incremental: task.incremental,
                                  auto_snapshot: task.auto_snapshot,
                                  encryption: task.encryption,
                                  enabled: task.enabled,
                                })
                                setShowCreateReplication(true)
                              }}
                              className="p-1.5 hover:bg-[#2a3b4d] rounded text-text-secondary hover:text-white transition-colors"
                              title="Edit"
                            >
                              <Edit size={18} />
                            </button>
                            <button
                              onClick={async () => {
                                if (confirm(`Delete replication task "${task.name}"?`)) {
                                  try {
                                    await replicationApi.deleteTask(task.id)
                                    await queryClient.invalidateQueries({ queryKey: ['replication-tasks'] })
                                    await refetchReplications()
                                    alert('Replication task deleted successfully')
                                  } catch (error: any) {
                                    alert(error.response?.data?.error || 'Failed to delete replication task')
                                  }
                                }
                              }}
                              className="p-1.5 hover:bg-red-500/20 rounded text-text-secondary hover:text-red-500 transition-colors"
                              title="Delete"
                            >
                              <Trash2 size={18} />
                            </button>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </div>

                {/* Inbound Replication Section */}
                <div>
                  <div className="flex items-center gap-2 mb-4">
                    <CloudSync size={20} className="text-emerald-500" />
                    <h4 className="text-white text-base font-bold">Inbound Replication</h4>
                    <span className="text-text-secondary text-sm">(Receiving from remote)</span>
                  </div>
                  {replicationLoading ? (
                    <div className="text-center py-8 text-text-secondary">Loading replication tasks...</div>
                  ) : inboundTasks.length === 0 ? (
                    <div className="text-center py-8 text-text-secondary bg-[#111a22] rounded-lg border border-[#2a3b4d]">
                      No inbound replication tasks configured.
                    </div>
                  ) : (
                    <div className="space-y-3">
                      {inboundTasks.map((task) => (
                        <div
                          key={task.id}
                          className="flex items-center gap-4 bg-[#111a22] p-4 rounded-lg border border-[#2a3b4d] hover:bg-[#1e2936] transition-colors"
                        >
                          <div
                            className={`w-2 h-2 rounded-full ${
                              task.status === 'running'
                                ? 'bg-primary animate-pulse'
                                : task.status === 'failed'
                                ? 'bg-red-500'
                                : 'bg-emerald-500'
                            }`}
                          ></div>
                          <div className="flex-1">
                            <div className="flex items-center gap-2">
                              <p className="text-white text-sm font-medium">{task.name}</p>
                              {!task.enabled && (
                                <span className="px-2 py-0.5 rounded text-[10px] font-bold bg-gray-500/20 text-gray-400">
                                  Disabled
                                </span>
                              )}
                            </div>
                            <p className="text-[#536b85] text-xs mt-1">
                              Source: {task.source_host}:{task.source_port} ({task.source_dataset}) → Local: {task.local_dataset}
                            </p>
                            {task.last_run_at && (
                              <p className="text-[#536b85] text-xs mt-1">
                                Last run: {new Date(task.last_run_at).toLocaleString()}
                                {task.last_run_status && (
                                  <span className={`ml-2 ${task.last_run_status === 'success' ? 'text-emerald-400' : 'text-red-400'}`}>
                                    ({task.last_run_status})
                                  </span>
                                )}
                              </p>
                            )}
                          </div>
                          <div className="flex items-center gap-2">
                            <button
                              onClick={() => {
                                setEditingReplication(task)
                                setReplicationForm({
                                  name: task.name,
                                  direction: task.direction,
                                  source_dataset: task.source_dataset,
                                  target_host: task.target_host,
                                  target_port: task.target_port,
                                  target_user: task.target_user,
                                  target_dataset: task.target_dataset,
                                  source_host: task.source_host,
                                  source_port: task.source_port,
                                  source_user: task.source_user,
                                  local_dataset: task.local_dataset,
                                  schedule_type: task.schedule_type,
                                  schedule_config: task.schedule_config,
                                  compression: task.compression,
                                  recursive: task.recursive,
                                  incremental: task.incremental,
                                  auto_snapshot: task.auto_snapshot,
                                  encryption: task.encryption,
                                  enabled: task.enabled,
                                })
                                setShowCreateReplication(true)
                              }}
                              className="p-1.5 hover:bg-[#2a3b4d] rounded text-text-secondary hover:text-white transition-colors"
                              title="Edit"
                            >
                              <Edit size={18} />
                            </button>
                            <button
                              onClick={async () => {
                                if (confirm(`Delete replication task "${task.name}"?`)) {
                                  try {
                                    await replicationApi.deleteTask(task.id)
                                    await queryClient.invalidateQueries({ queryKey: ['replication-tasks'] })
                                    await refetchReplications()
                                    alert('Replication task deleted successfully')
                                  } catch (error: any) {
                                    alert(error.response?.data?.error || 'Failed to delete replication task')
                                  }
                                }
                              }}
                              className="p-1.5 hover:bg-red-500/20 rounded text-text-secondary hover:text-red-500 transition-colors"
                              title="Delete"
                            >
                              <Trash2 size={18} />
                            </button>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            )}

            {activeTab === 'restore' && (
              <div className="p-8 text-center">
                <RotateCcw className="mx-auto mb-4 text-text-secondary" size={48} />
                <p className="text-text-secondary text-sm">Restore points coming soon</p>
              </div>
            )}
          </div>

          {/* Bottom Info / Replication Quick Status */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
            {/* Replication Status */}
            <div className="bg-[#18232e] border border-[#2a3b4d] rounded-xl p-6">
              <div className="flex items-center justify-between mb-4">
                <h3 className="text-white font-bold text-lg">Replication Status</h3>
                <a className="text-primary text-sm font-bold hover:underline" href="#">
                  Manage All
                </a>
              </div>
              <div className="flex flex-col gap-4">
                {allReplicationTasks.slice(0, 3).map((task) => (
                  <div
                    key={task.id}
                    className="flex items-center gap-4 bg-[#111a22] p-3 rounded-lg border border-[#2a3b4d]"
                  >
                    <div
                      className={`w-2 h-2 rounded-full ${
                        task.status === 'running'
                          ? 'bg-primary animate-pulse'
                          : task.status === 'failed'
                          ? 'bg-red-500'
                          : 'bg-emerald-500'
                      }`}
                    ></div>
                    <div className="flex-1">
                      <p className="text-white text-sm font-medium">{task.name}</p>
                      <p className="text-[#536b85] text-xs">
                        {task.direction === 'outbound' 
                          ? `Target: ${task.target_host}:${task.target_port}` 
                          : `Source: ${task.source_host}:${task.source_port}`}
                      </p>
                    </div>
                    <div className="text-right">
                      <p
                        className={`text-sm ${
                          task.status === 'running' ? 'text-primary font-bold' : 'text-text-secondary'
                        }`}
                      >
                        {task.status === 'running' ? 'Running' : task.status}
                      </p>
                      {task.last_run_at && (
                        <p className="text-[#536b85] text-xs">
                          {new Date(task.last_run_at).toLocaleString()}
                        </p>
                      )}
                    </div>
                  </div>
                ))}
                {allReplicationTasks.length === 0 && (
                  <p className="text-text-secondary text-sm text-center py-4">No replication tasks</p>
                )}
              </div>
            </div>

            {/* Snapshot Retention */}
            <div className="bg-[#18232e] border border-[#2a3b4d] rounded-xl p-6 flex flex-col justify-center items-center text-center">
              <div className="w-12 h-12 bg-primary/10 rounded-full flex items-center justify-center mb-3">
                <AlertCircle className="text-primary text-2xl" />
              </div>
              <h3 className="text-white font-bold text-lg">Snapshot Retention</h3>
              <p className="text-text-secondary text-sm mt-1 mb-4">
                You have 14 snapshots marked for expiration in the next 24 hours.
              </p>
              <button className="text-white bg-[#2a3b4d] hover:bg-[#324d67] px-4 py-2 rounded-lg text-sm font-medium transition-colors">
                Review Expiration Policy
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* Create Replication Modal */}
      {showCreateReplication && (
        <div
          className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4"
          onClick={() => setShowCreateReplication(false)}
        >
          <div
            className="bg-[#18232e] rounded-xl border border-[#2a3b4d] max-w-2xl w-full max-h-[90vh] overflow-y-auto"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="p-6 border-b border-[#2a3b4d] flex justify-between items-center">
              <h3 className="text-lg font-bold text-white">
                {editingReplication ? 'Edit Replication Task' : 'Create Replication Task'}
              </h3>
              <button
                onClick={() => {
                  setShowCreateReplication(false)
                  setEditingReplication(null)
                  setReplicationForm({
                    name: '',
                    direction: 'outbound',
                    source_dataset: '',
                    target_host: '',
                    target_port: 22,
                    target_user: 'root',
                    target_dataset: '',
                    source_host: '',
                    source_port: 22,
                    source_user: 'root',
                    local_dataset: '',
                    schedule_type: 'daily',
                    schedule_config: { time: '00:00' },
                    compression: 'lz4',
                    recursive: false,
                    incremental: true,
                    auto_snapshot: true,
                    encryption: false,
                    enabled: true,
                  })
                }}
                className="text-text-secondary hover:text-white"
              >
                <X size={20} />
              </button>
            </div>
            <div className="p-6 flex flex-col gap-4">
              {/* Task Name */}
              <div className="flex flex-col gap-2">
                <label className="text-sm font-semibold text-white">Task Name</label>
                <input
                  className="w-full bg-[#111a22] border border-[#2a3b4d] rounded-lg px-3 py-2 text-sm text-white focus:border-primary focus:ring-1 focus:ring-primary outline-none"
                  type="text"
                  placeholder="Daily Offsite Backup"
                  value={replicationForm.name}
                  onChange={(e) => setReplicationForm({ ...replicationForm, name: e.target.value })}
                />
              </div>

              {/* Direction */}
              <div className="flex flex-col gap-2">
                <label className="text-sm font-semibold text-white">Direction</label>
                <select
                  className="w-full bg-[#111a22] border border-[#2a3b4d] rounded-lg px-3 py-2 text-sm text-white focus:border-primary focus:ring-1 focus:ring-primary outline-none appearance-none"
                  value={replicationForm.direction}
                  onChange={(e) => setReplicationForm({ ...replicationForm, direction: e.target.value as 'outbound' | 'inbound' })}
                >
                  <option value="outbound">Outbound (Sending to remote)</option>
                  <option value="inbound">Inbound (Receiving from remote)</option>
                </select>
              </div>

              {/* Outbound Fields */}
              {replicationForm.direction === 'outbound' && (
                <>
                  {/* Source Dataset */}
                  <div className="flex flex-col gap-2">
                    <label className="text-sm font-semibold text-white">Source Dataset</label>
                    <select
                      className="w-full bg-[#111a22] border border-[#2a3b4d] rounded-lg px-3 py-2 text-sm text-white focus:border-primary focus:ring-1 focus:ring-primary outline-none appearance-none"
                      value={replicationForm.source_dataset || ''}
                      onChange={(e) => {
                        setReplicationForm({ ...replicationForm, source_dataset: e.target.value || undefined })
                        const poolName = e.target.value.split('/')[0]
                        if (poolName) {
                          fetchDatasets(poolName)
                        }
                      }}
                    >
                      <option value="">Select a dataset</option>
                      {pools.map((pool) => (
                        <optgroup key={pool.id} label={pool.name}>
                          {datasets
                            .find((d) => d.pool === pool.name)
                            ?.datasets.filter((ds) => ds.type === 'filesystem')
                            .map((ds) => (
                              <option key={ds.id} value={ds.name}>
                                {ds.name}
                              </option>
                            ))}
                        </optgroup>
                      ))}
                    </select>
                  </div>
                </>
              )}

              {/* Inbound Fields */}
              {replicationForm.direction === 'inbound' && (
                <>
                  {/* Source Host */}
                  <div className="flex flex-col gap-2">
                    <label className="text-sm font-semibold text-white">Source Host</label>
                    <input
                      className="w-full bg-[#111a22] border border-[#2a3b4d] rounded-lg px-3 py-2 text-sm text-white focus:border-primary focus:ring-1 focus:ring-primary outline-none font-mono"
                      type="text"
                      placeholder="192.168.20.5"
                      value={replicationForm.source_host || ''}
                      onChange={(e) => setReplicationForm({ ...replicationForm, source_host: e.target.value || undefined })}
                    />
                  </div>
                  {/* Source Dataset for Inbound */}
                  <div className="flex flex-col gap-2">
                    <label className="text-sm font-semibold text-white">Source Dataset (on remote)</label>
                    <input
                      className="w-full bg-[#111a22] border border-[#2a3b4d] rounded-lg px-3 py-2 text-sm text-white focus:border-primary focus:ring-1 focus:ring-primary outline-none font-mono"
                      type="text"
                      placeholder="tank/backup"
                      value={replicationForm.source_dataset || ''}
                      onChange={(e) => setReplicationForm({ ...replicationForm, source_dataset: e.target.value || undefined })}
                    />
                  </div>
                  {/* Local Dataset */}
                  <div className="flex flex-col gap-2">
                    <label className="text-sm font-semibold text-white">Local Dataset</label>
                    <select
                      className="w-full bg-[#111a22] border border-[#2a3b4d] rounded-lg px-3 py-2 text-sm text-white focus:border-primary focus:ring-1 focus:ring-primary outline-none appearance-none"
                      value={replicationForm.local_dataset || ''}
                      onChange={(e) => {
                        setReplicationForm({ ...replicationForm, local_dataset: e.target.value || undefined })
                        const poolName = e.target.value.split('/')[0]
                        if (poolName) {
                          fetchDatasets(poolName)
                        }
                      }}
                    >
                      <option value="">Select a dataset</option>
                      {pools.map((pool) => (
                        <optgroup key={pool.id} label={pool.name}>
                          {datasets
                            .find((d) => d.pool === pool.name)
                            ?.datasets.filter((ds) => ds.type === 'filesystem')
                            .map((ds) => (
                              <option key={ds.id} value={ds.name}>
                                {ds.name}
                              </option>
                            ))}
                        </optgroup>
                      ))}
                    </select>
                  </div>
                </>
              )}

              {/* Target Configuration (for Outbound) */}
              {replicationForm.direction === 'outbound' && (
                <>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div className="flex flex-col gap-2">
                      <label className="text-sm font-semibold text-white">Target Host</label>
                      <input
                        className="w-full bg-[#111a22] border border-[#2a3b4d] rounded-lg px-3 py-2 text-sm text-white focus:border-primary focus:ring-1 focus:ring-primary outline-none font-mono"
                        type="text"
                        placeholder="192.168.20.5"
                        value={replicationForm.target_host || ''}
                        onChange={(e) => setReplicationForm({ ...replicationForm, target_host: e.target.value || undefined })}
                      />
                    </div>
                    <div className="flex flex-col gap-2">
                      <label className="text-sm font-semibold text-white">SSH Port</label>
                      <input
                        className="w-full bg-[#111a22] border border-[#2a3b4d] rounded-lg px-3 py-2 text-sm text-white focus:border-primary focus:ring-1 focus:ring-primary outline-none font-mono"
                        type="number"
                        placeholder="22"
                        value={replicationForm.target_port || 22}
                        onChange={(e) => setReplicationForm({ ...replicationForm, target_port: parseInt(e.target.value) || 22 })}
                      />
                    </div>
                  </div>

                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div className="flex flex-col gap-2">
                      <label className="text-sm font-semibold text-white">Target User</label>
                      <input
                        className="w-full bg-[#111a22] border border-[#2a3b4d] rounded-lg px-3 py-2 text-sm text-white focus:border-primary focus:ring-1 focus:ring-primary outline-none"
                        type="text"
                        placeholder="root"
                        value={replicationForm.target_user || 'root'}
                        onChange={(e) => setReplicationForm({ ...replicationForm, target_user: e.target.value || undefined })}
                      />
                    </div>
                    <div className="flex flex-col gap-2">
                      <label className="text-sm font-semibold text-white">Target Dataset</label>
                      <input
                        className="w-full bg-[#111a22] border border-[#2a3b4d] rounded-lg px-3 py-2 text-sm text-white focus:border-primary focus:ring-1 focus:ring-primary outline-none font-mono"
                        type="text"
                        placeholder="tank/backup"
                        value={replicationForm.target_dataset || ''}
                        onChange={(e) => setReplicationForm({ ...replicationForm, target_dataset: e.target.value || undefined })}
                      />
                    </div>
                  </div>
                </>
              )}

              {/* Schedule */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="flex flex-col gap-2">
                  <label className="text-sm font-semibold text-white">Schedule</label>
                  <select
                    className="w-full bg-[#111a22] border border-[#2a3b4d] rounded-lg px-3 py-2 text-sm text-white focus:border-primary focus:ring-1 focus:ring-primary outline-none appearance-none"
                    value={replicationForm.schedule_type || 'daily'}
                    onChange={(e) => setReplicationForm({ ...replicationForm, schedule_type: e.target.value || undefined })}
                  >
                    <option value="hourly">Hourly</option>
                    <option value="daily">Daily</option>
                    <option value="weekly">Weekly</option>
                    <option value="monthly">Monthly</option>
                    <option value="cron">Custom (Cron)</option>
                  </select>
                </div>
                <div className="flex flex-col gap-2">
                  <label className="text-sm font-semibold text-white">Time</label>
                  <input
                    className="w-full bg-[#111a22] border border-[#2a3b4d] rounded-lg px-3 py-2 text-sm text-white focus:border-primary focus:ring-1 focus:ring-primary outline-none font-mono"
                    type="time"
                    value={replicationForm.schedule_config?.time || '00:00'}
                    onChange={(e) => setReplicationForm({ 
                      ...replicationForm, 
                      schedule_config: { ...replicationForm.schedule_config, time: e.target.value } 
                    })}
                  />
                </div>
              </div>

              {/* Options */}
              <div className="flex flex-col gap-2">
                <label className="text-sm font-semibold text-white">Compression</label>
                <select
                  className="w-full bg-[#111a22] border border-[#2a3b4d] rounded-lg px-3 py-2 text-sm text-white focus:border-primary focus:ring-1 focus:ring-primary outline-none appearance-none"
                  value={replicationForm.compression}
                  onChange={(e) => setReplicationForm({ ...replicationForm, compression: e.target.value })}
                >
                  <option value="off">Off</option>
                  <option value="lz4">LZ4 (Fast)</option>
                  <option value="gzip">GZIP</option>
                  <option value="zstd">ZSTD</option>
                </select>
              </div>

              {/* Checkboxes */}
              <div className="flex flex-col gap-3">
                <label className="flex items-center gap-2 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={replicationForm.recursive}
                    onChange={(e) => setReplicationForm({ ...replicationForm, recursive: e.target.checked })}
                    className="rounded border-[#324d67] bg-[#111a22] text-primary focus:ring-primary h-4 w-4"
                  />
                  <span className="text-sm text-white">Recursive (include child datasets)</span>
                </label>
                <label className="flex items-center gap-2 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={replicationForm.auto_snapshot || false}
                    onChange={(e) => setReplicationForm({ ...replicationForm, auto_snapshot: e.target.checked })}
                    className="rounded border-[#324d67] bg-[#111a22] text-primary focus:ring-primary h-4 w-4"
                  />
                  <span className="text-sm text-white">Auto-create snapshot before replication</span>
                </label>
                <label className="flex items-center gap-2 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={replicationForm.encryption}
                    onChange={(e) => setReplicationForm({ ...replicationForm, encryption: e.target.checked })}
                    className="rounded border-[#324d67] bg-[#111a22] text-primary focus:ring-primary h-4 w-4"
                  />
                  <span className="text-sm text-white">Enable encryption (SSH tunnel)</span>
                </label>
              </div>

              {/* Action Buttons */}
              <div className="flex justify-end gap-3 pt-4 border-t border-[#2a3b4d]">
                <Button
                  onClick={() => setShowCreateReplication(false)}
                  variant="outline"
                  className="px-4 h-10 border-[#2a3b4d] text-white hover:bg-[#2a3b4d]"
                >
                  Cancel
                </Button>
                <Button
                  onClick={async () => {
                    try {
                      if (editingReplication) {
                        await replicationApi.updateTask(editingReplication.id, replicationForm)
                        alert('Replication task updated successfully!')
                      } else {
                        await replicationApi.createTask(replicationForm)
                        alert('Replication task created successfully!')
                      }
                      await queryClient.invalidateQueries({ queryKey: ['replication-tasks'] })
                      await refetchReplications()
                      setShowCreateReplication(false)
                      setEditingReplication(null)
                      setReplicationForm({
                        name: '',
                        direction: 'outbound',
                        source_dataset: '',
                        target_host: '',
                        target_port: 22,
                        target_user: 'root',
                        target_dataset: '',
                        source_host: '',
                        source_port: 22,
                        source_user: 'root',
                        local_dataset: '',
                        schedule_type: 'daily',
                        schedule_config: { time: '00:00' },
                        compression: 'lz4',
                        recursive: false,
                        incremental: true,
                        auto_snapshot: true,
                        encryption: false,
                        enabled: true,
                      })
                    } catch (error: any) {
                      alert(error.response?.data?.error || 'Failed to save replication task')
                    }
                  }}
                  className="px-4 h-10 bg-primary hover:bg-blue-600"
                >
                  <Save size={18} className="mr-2" />
                  {editingReplication ? 'Update Replication' : 'Create Replication'}
                </Button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Create Snapshot Modal */}
      {showCreateSnapshot && (
        <div
          className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4"
          onClick={() => {
            setShowCreateSnapshot(false)
            setSnapshotForm({ dataset: '', name: '', recursive: false })
          }}
        >
          <div
            className="bg-[#18232e] rounded-xl border border-[#2a3b4d] max-w-lg w-full"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="p-6 border-b border-[#2a3b4d] flex justify-between items-center">
              <h3 className="text-lg font-bold text-white">Create Snapshot</h3>
              <button
                onClick={() => {
                  setShowCreateSnapshot(false)
                  setSnapshotForm({ dataset: '', name: '', recursive: false })
                }}
                className="text-text-secondary hover:text-white"
              >
                <X size={20} />
              </button>
            </div>
            <div className="p-6 flex flex-col gap-4">
              <div className="flex flex-col gap-2">
                <label className="text-sm font-semibold text-white">Dataset</label>
                <select
                  className="w-full bg-[#111a22] border border-[#2a3b4d] rounded-lg px-3 py-2 text-sm text-white focus:border-primary focus:ring-1 focus:ring-primary outline-none"
                  value={snapshotForm.dataset}
                  onChange={(e) => {
                    setSnapshotForm({ ...snapshotForm, dataset: e.target.value })
                  }}
                  onFocus={() => {
                    // Fetch datasets when dropdown is opened if not already loaded
                    if (datasets.length === 0) {
                      fetchAllDatasets()
                    }
                  }}
                >
                  <option value="">Select a dataset</option>
                  {pools.map((pool) => {
                    const poolDatasets = datasets.find((d) => d.pool === pool.name || d.pool === pool.id)
                    if (!poolDatasets || poolDatasets.datasets.length === 0) {
                      return (
                        <optgroup key={pool.id} label={pool.name}>
                          <option value="" disabled>Loading datasets...</option>
                        </optgroup>
                      )
                    }
                    return (
                      <optgroup key={pool.id} label={pool.name}>
                        {poolDatasets.datasets
                          .filter((ds) => ds.type === 'filesystem')
                          .map((ds) => (
                            <option key={ds.id} value={ds.name}>
                              {ds.name}
                            </option>
                          ))}
                      </optgroup>
                    )
                  })}
                </select>
              </div>
              <div className="flex flex-col gap-2">
                <label className="text-sm font-semibold text-white">Snapshot Name</label>
                <input
                  className="w-full bg-[#111a22] border border-[#2a3b4d] rounded-lg px-3 py-2 text-sm text-white focus:border-primary focus:ring-1 focus:ring-primary outline-none"
                  type="text"
                  placeholder="manual-backup-2024"
                  value={snapshotForm.name}
                  onChange={(e) => setSnapshotForm({ ...snapshotForm, name: e.target.value })}
                />
              </div>
              <div className="flex items-center gap-2">
                <input
                  type="checkbox"
                  className="w-4 h-4 rounded border-[#324d67] bg-[#111a22] text-primary"
                  checked={snapshotForm.recursive}
                  onChange={(e) => setSnapshotForm({ ...snapshotForm, recursive: e.target.checked })}
                />
                <label className="text-sm text-white">Recursive (include child datasets)</label>
              </div>
              <div className="flex justify-end gap-3 pt-4">
                <Button
                  onClick={() => {
                    setShowCreateSnapshot(false)
                    setSnapshotForm({ dataset: '', name: '', recursive: false })
                  }}
                  variant="outline"
                  className="px-4 h-10 border-[#2a3b4d] text-white hover:bg-[#2a3b4d]"
                >
                  Cancel
                </Button>
                <Button
                  onClick={() => {
                    if (!snapshotForm.dataset || !snapshotForm.name) {
                      alert('Please fill in all required fields')
                      return
                    }
                    createSnapshotMutation.mutate({
                      dataset: snapshotForm.dataset,
                      name: snapshotForm.name,
                      recursive: snapshotForm.recursive,
                    })
                  }}
                  disabled={createSnapshotMutation.isPending || !snapshotForm.dataset || !snapshotForm.name}
                  className="px-4 h-10 bg-primary hover:bg-blue-600 disabled:opacity-50"
                >
                  {createSnapshotMutation.isPending ? 'Creating...' : 'Create Snapshot'}
                </Button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Delete Snapshot Confirmation Dialog */}
      {deleteConfirmSnapshot && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-[#18232e] border border-[#2a3b4d] rounded-lg p-6 max-w-md w-full mx-4">
            <div className="flex items-center justify-between mb-6">
              <h2 className="text-white text-xl font-bold">Confirm Delete Snapshot</h2>
              <button
                onClick={() => setDeleteConfirmSnapshot(null)}
                className="text-text-secondary hover:text-white transition-colors"
              >
                ✕
              </button>
            </div>
            <div className="space-y-4">
              <div className="bg-red-500/10 border border-red-500/20 rounded-lg p-4">
                <div className="flex items-start gap-2">
                  <AlertCircle className="text-red-400 mt-0.5" size={20} />
                  <div>
                    <p className="text-red-400 text-sm font-medium mb-1">Warning</p>
                    <p className="text-red-300 text-xs">
                      This action cannot be undone. Snapshot "{deleteConfirmSnapshot}" will be permanently deleted.
                    </p>
                  </div>
                </div>
              </div>
              <div className="flex gap-3 justify-end pt-4">
                <button
                  onClick={() => setDeleteConfirmSnapshot(null)}
                  className="px-4 py-2 text-white text-sm font-medium rounded-lg border border-[#2a3b4d] hover:bg-[#111a22] transition-colors"
                >
                  Cancel
                </button>
                <button
                  onClick={() => {
                    deleteSnapshotMutation.mutate({ name: deleteConfirmSnapshot, recursive: false })
                  }}
                  disabled={deleteSnapshotMutation.isPending}
                  className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white text-sm font-medium rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {deleteSnapshotMutation.isPending ? 'Deleting...' : 'Delete Snapshot'}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Rollback Snapshot Confirmation Dialog */}
      {rollbackConfirmSnapshot && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-[#18232e] border border-[#2a3b4d] rounded-lg p-6 max-w-md w-full mx-4">
            <div className="flex items-center justify-between mb-6">
              <h2 className="text-white text-xl font-bold">Confirm Rollback to Snapshot</h2>
              <button
                onClick={() => setRollbackConfirmSnapshot(null)}
                className="text-text-secondary hover:text-white transition-colors"
              >
                ✕
              </button>
            </div>
            <div className="space-y-4">
              <div className="bg-orange-500/10 border border-orange-500/20 rounded-lg p-4">
                <div className="flex items-start gap-2">
                  <AlertCircle className="text-orange-400 mt-0.5" size={20} />
                  <div>
                    <p className="text-orange-400 text-sm font-medium mb-1">Warning</p>
                    <p className="text-orange-300 text-xs">
                      Rolling back to snapshot "{rollbackConfirmSnapshot}" will destroy all changes made after this snapshot was created. This action cannot be undone.
                    </p>
                  </div>
                </div>
              </div>
              <div className="flex gap-3 justify-end pt-4">
                <button
                  onClick={() => setRollbackConfirmSnapshot(null)}
                  className="px-4 py-2 text-white text-sm font-medium rounded-lg border border-[#2a3b4d] hover:bg-[#111a22] transition-colors"
                >
                  Cancel
                </button>
                <button
                  onClick={() => {
                    rollbackSnapshotMutation.mutate({ name: rollbackConfirmSnapshot, force: false })
                  }}
                  disabled={rollbackSnapshotMutation.isPending}
                  className="px-4 py-2 bg-orange-600 hover:bg-orange-700 text-white text-sm font-medium rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {rollbackSnapshotMutation.isPending ? 'Rolling back...' : 'Rollback to Snapshot'}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Create/Edit Schedule Modal */}
      {showCreateSchedule && (
        <div className="fixed inset-0 bg-black/60 backdrop-blur-sm z-50 flex items-center justify-center p-4">
          <div className="bg-[#18232e] border border-[#2a3b4d] rounded-xl shadow-xl w-full max-w-2xl max-h-[90vh] overflow-y-auto">
            <div className="p-6 border-b border-[#2a3b4d]">
              <div className="flex items-center justify-between">
                <h2 className="text-white text-xl font-bold">
                  {editingSchedule ? 'Edit Schedule' : 'Create Snapshot Schedule'}
                </h2>
                <button
                  onClick={() => {
                    setShowCreateSchedule(false)
                    setEditingSchedule(null)
                    setScheduleForm({
                      name: '',
                      dataset: '',
                      snapshot_name_template: 'auto-%Y-%m-%d-%H%M',
                      schedule_type: 'daily',
                      schedule_config: { time: '00:00' },
                      recursive: false,
                    })
                  }}
                  className="text-text-secondary hover:text-white transition-colors"
                >
                  <X size={24} />
                </button>
              </div>
            </div>
            <div className="p-6 space-y-4">
              {/* Name */}
              <div>
                <label className="text-sm font-semibold text-white mb-2 block">Schedule Name</label>
                <input
                  type="text"
                  value={scheduleForm.name}
                  onChange={(e) => setScheduleForm({ ...scheduleForm, name: e.target.value })}
                  placeholder="e.g., Daily Backup"
                  className="w-full px-4 py-2 bg-[#111a22] border border-[#2a3b4d] rounded-lg text-white placeholder-text-secondary focus:outline-none focus:border-primary"
                />
              </div>

              {/* Dataset */}
              <div>
                <label className="text-sm font-semibold text-white mb-2 block">Dataset</label>
                <select
                  value={scheduleForm.dataset}
                  onChange={(e) => setScheduleForm({ ...scheduleForm, dataset: e.target.value })}
                  className="w-full px-4 py-2 bg-[#111a22] border border-[#2a3b4d] rounded-lg text-white focus:outline-none focus:border-primary"
                >
                  <option value="">Select dataset...</option>
                  {datasets.flatMap((d) =>
                    d.datasets.map((ds: any) => (
                      <option key={ds.name} value={ds.name}>
                        {ds.name}
                      </option>
                    ))
                  )}
                </select>
              </div>

              {/* Snapshot Name Template */}
              <div>
                <label className="text-sm font-semibold text-white mb-2 block">Snapshot Name Template</label>
                <input
                  type="text"
                  value={scheduleForm.snapshot_name_template}
                  onChange={(e) => setScheduleForm({ ...scheduleForm, snapshot_name_template: e.target.value })}
                  placeholder="e.g., auto-%Y-%m-%d-%H%M or daily-backup"
                  className="w-full px-4 py-2 bg-[#111a22] border border-[#2a3b4d] rounded-lg text-white placeholder-text-secondary focus:outline-none focus:border-primary"
                />
                <p className="text-[#536b85] text-xs mt-1">
                  Use %Y, %m, %d, %H, %M for date/time formatting (e.g., %Y-%m-%d-%H%M)
                </p>
              </div>

              {/* Schedule Type */}
              <div>
                <label className="text-sm font-semibold text-white mb-2 block">Schedule Type</label>
                <select
                  value={scheduleForm.schedule_type}
                  onChange={(e) => {
                    const newType = e.target.value as any
                    let newConfig: any = {}
                    if (newType === 'daily' || newType === 'weekly' || newType === 'monthly') {
                      newConfig = { time: scheduleForm.schedule_config?.time || '00:00' }
                      if (newType === 'weekly') {
                        newConfig.day = scheduleForm.schedule_config?.day || 0
                      } else if (newType === 'monthly') {
                        newConfig.day = scheduleForm.schedule_config?.day || 1
                      }
                    } else if (newType === 'cron') {
                      newConfig = { cron: scheduleForm.schedule_config?.cron || '0 0 * * *' }
                    }
                    setScheduleForm({ ...scheduleForm, schedule_type: newType, schedule_config: newConfig })
                  }}
                  className="w-full px-4 py-2 bg-[#111a22] border border-[#2a3b4d] rounded-lg text-white focus:outline-none focus:border-primary"
                >
                  <option value="hourly">Hourly</option>
                  <option value="daily">Daily</option>
                  <option value="weekly">Weekly</option>
                  <option value="monthly">Monthly</option>
                  <option value="cron">Custom (Cron)</option>
                </select>
              </div>

              {/* Schedule Config */}
              {scheduleForm.schedule_type === 'daily' && (
                <div>
                  <label className="text-sm font-semibold text-white mb-2 block">Time (HH:MM)</label>
                  <input
                    type="time"
                    value={scheduleForm.schedule_config?.time || '00:00'}
                    onChange={(e) =>
                      setScheduleForm({
                        ...scheduleForm,
                        schedule_config: { ...scheduleForm.schedule_config, time: e.target.value },
                      })
                    }
                    className="w-full px-4 py-2 bg-[#111a22] border border-[#2a3b4d] rounded-lg text-white focus:outline-none focus:border-primary"
                  />
                </div>
              )}

              {scheduleForm.schedule_type === 'weekly' && (
                <>
                  <div>
                    <label className="text-sm font-semibold text-white mb-2 block">Day of Week</label>
                    <select
                      value={scheduleForm.schedule_config?.day || 0}
                      onChange={(e) =>
                        setScheduleForm({
                          ...scheduleForm,
                          schedule_config: { ...scheduleForm.schedule_config, day: parseInt(e.target.value) },
                        })
                      }
                      className="w-full px-4 py-2 bg-[#111a22] border border-[#2a3b4d] rounded-lg text-white focus:outline-none focus:border-primary"
                    >
                      <option value={0}>Sunday</option>
                      <option value={1}>Monday</option>
                      <option value={2}>Tuesday</option>
                      <option value={3}>Wednesday</option>
                      <option value={4}>Thursday</option>
                      <option value={5}>Friday</option>
                      <option value={6}>Saturday</option>
                    </select>
                  </div>
                  <div>
                    <label className="text-sm font-semibold text-white mb-2 block">Time (HH:MM)</label>
                    <input
                      type="time"
                      value={scheduleForm.schedule_config?.time || '00:00'}
                      onChange={(e) =>
                        setScheduleForm({
                          ...scheduleForm,
                          schedule_config: { ...scheduleForm.schedule_config, time: e.target.value },
                        })
                      }
                      className="w-full px-4 py-2 bg-[#111a22] border border-[#2a3b4d] rounded-lg text-white focus:outline-none focus:border-primary"
                    />
                  </div>
                </>
              )}

              {scheduleForm.schedule_type === 'monthly' && (
                <>
                  <div>
                    <label className="text-sm font-semibold text-white mb-2 block">Day of Month (1-31)</label>
                    <input
                      type="number"
                      min="1"
                      max="31"
                      value={scheduleForm.schedule_config?.day || 1}
                      onChange={(e) =>
                        setScheduleForm({
                          ...scheduleForm,
                          schedule_config: { ...scheduleForm.schedule_config, day: parseInt(e.target.value) },
                        })
                      }
                      className="w-full px-4 py-2 bg-[#111a22] border border-[#2a3b4d] rounded-lg text-white focus:outline-none focus:border-primary"
                    />
                  </div>
                  <div>
                    <label className="text-sm font-semibold text-white mb-2 block">Time (HH:MM)</label>
                    <input
                      type="time"
                      value={scheduleForm.schedule_config?.time || '00:00'}
                      onChange={(e) =>
                        setScheduleForm({
                          ...scheduleForm,
                          schedule_config: { ...scheduleForm.schedule_config, time: e.target.value },
                        })
                      }
                      className="w-full px-4 py-2 bg-[#111a22] border border-[#2a3b4d] rounded-lg text-white focus:outline-none focus:border-primary"
                    />
                  </div>
                </>
              )}

              {scheduleForm.schedule_type === 'cron' && (
                <div>
                  <label className="text-sm font-semibold text-white mb-2 block">Cron Expression</label>
                  <input
                    type="text"
                    value={scheduleForm.schedule_config?.cron || '0 0 * * *'}
                    onChange={(e) =>
                      setScheduleForm({
                        ...scheduleForm,
                        schedule_config: { ...scheduleForm.schedule_config, cron: e.target.value },
                      })
                    }
                    placeholder="0 0 * * *"
                    className="w-full px-4 py-2 bg-[#111a22] border border-[#2a3b4d] rounded-lg text-white placeholder-text-secondary focus:outline-none focus:border-primary"
                  />
                  <p className="text-[#536b85] text-xs mt-1">Format: minute hour day month weekday</p>
                </div>
              )}

              {/* Recursive */}
              <div className="flex items-center gap-2">
                <input
                  type="checkbox"
                  id="recursive"
                  checked={scheduleForm.recursive}
                  onChange={(e) => setScheduleForm({ ...scheduleForm, recursive: e.target.checked })}
                  className="w-4 h-4 rounded border-[#2a3b4d] bg-[#111a22] text-primary focus:ring-primary"
                />
                <label htmlFor="recursive" className="text-sm text-white">
                  Recursive (include child datasets)
                </label>
              </div>

              {/* Retention Count */}
              <div>
                <label className="text-sm font-semibold text-white mb-2 block">Retention Count (optional)</label>
                <input
                  type="number"
                  min="1"
                  value={scheduleForm.retention_count || ''}
                  onChange={(e) =>
                    setScheduleForm({
                      ...scheduleForm,
                      retention_count: e.target.value ? parseInt(e.target.value) : undefined,
                    })
                  }
                  placeholder="Keep last N snapshots (leave empty for unlimited)"
                  className="w-full px-4 py-2 bg-[#111a22] border border-[#2a3b4d] rounded-lg text-white placeholder-text-secondary focus:outline-none focus:border-primary"
                />
              </div>

              {/* Retention Days */}
              <div>
                <label className="text-sm font-semibold text-white mb-2 block">Retention Days (optional)</label>
                <input
                  type="number"
                  min="1"
                  value={scheduleForm.retention_days || ''}
                  onChange={(e) =>
                    setScheduleForm({
                      ...scheduleForm,
                      retention_days: e.target.value ? parseInt(e.target.value) : undefined,
                    })
                  }
                  placeholder="Keep snapshots for N days (leave empty for unlimited)"
                  className="w-full px-4 py-2 bg-[#111a22] border border-[#2a3b4d] rounded-lg text-white placeholder-text-secondary focus:outline-none focus:border-primary"
                />
              </div>

              {/* Buttons */}
              <div className="flex gap-3 justify-end pt-4">
                <button
                  onClick={() => {
                    setShowCreateSchedule(false)
                    setEditingSchedule(null)
                    setScheduleForm({
                      name: '',
                      dataset: '',
                      snapshot_name_template: 'auto-%Y-%m-%d-%H%M',
                      schedule_type: 'daily',
                      schedule_config: { time: '00:00' },
                      recursive: false,
                    })
                  }}
                  className="px-4 py-2 text-white text-sm font-medium rounded-lg border border-[#2a3b4d] hover:bg-[#111a22] transition-colors"
                >
                  Cancel
                </button>
                <button
                  onClick={async () => {
                    if (!scheduleForm.name || !scheduleForm.dataset || !scheduleForm.snapshot_name_template) {
                      alert('Please fill in all required fields')
                      return
                    }

                    try {
                      if (editingSchedule) {
                        await snapshotScheduleApi.updateSchedule(editingSchedule.id, scheduleForm)
                        alert('Schedule updated successfully!')
                      } else {
                        await snapshotScheduleApi.createSchedule(scheduleForm)
                        alert('Schedule created successfully!')
                      }
                      // Invalidate and refetch schedules immediately
                      await queryClient.invalidateQueries({ queryKey: ['snapshot-schedules'] })
                      await refetchSchedules()
                      setShowCreateSchedule(false)
                      setEditingSchedule(null)
                      setScheduleForm({
                        name: '',
                        dataset: '',
                        snapshot_name_template: 'auto-%Y-%m-%d-%H%M',
                        schedule_type: 'daily',
                        schedule_config: { time: '00:00' },
                        recursive: false,
                      })
                    } catch (error: any) {
                      alert(error.response?.data?.error || 'Failed to save schedule')
                    }
                  }}
                  className="px-4 py-2 bg-primary hover:bg-blue-600 text-white text-sm font-medium rounded-lg transition-colors"
                >
                  {editingSchedule ? 'Update Schedule' : 'Create Schedule'}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

