import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { formatBytes } from '@/lib/format'
import { zfsApi } from '@/api/storage'
import {
  Camera,
  History,
  Plus,
  Search,
  Filter,
  Calendar,
  RotateCcw,
  Copy,
  Trash2,
  RefreshCw,
  Clock,
  TrendingUp,
  CloudSync,
  AlertCircle,
  MoreVertical,
  X,
  Save
} from 'lucide-react'
import { Link } from 'react-router-dom'
import { ChevronRight } from 'lucide-react'
import { Button } from '@/components/ui/button'

// Mock data - will be replaced with API calls
const MOCK_SNAPSHOTS = [
  {
    id: '1',
    name: 'auto-2023-10-27-0000',
    dataset: 'tank/home',
    created: '2023-10-27T00:00:00Z',
    referenced: 1.2 * 1024 * 1024, // 1.2 MB
    isLatest: true,
  },
  {
    id: '2',
    name: 'manual-backup-pre-upgrade',
    dataset: 'tank/services/db',
    created: '2023-10-26T16:30:00Z',
    referenced: 4.5 * 1024 * 1024 * 1024, // 4.5 GB
    isLatest: false,
  },
  {
    id: '3',
    name: 'auto-2023-10-26-0000',
    dataset: 'tank/home',
    created: '2023-10-26T00:00:00Z',
    referenced: 850 * 1024, // 850 KB
    isLatest: false,
  },
  {
    id: '4',
    name: 'auto-2023-10-25-0000',
    dataset: 'tank/home',
    created: '2023-10-25T00:00:00Z',
    referenced: 1.1 * 1024 * 1024, // 1.1 MB
    isLatest: false,
  },
  {
    id: '5',
    name: 'auto-2023-10-24-0000',
    dataset: 'tank/home',
    created: '2023-10-24T00:00:00Z',
    referenced: 920 * 1024, // 920 KB
    isLatest: false,
  },
]

const MOCK_REPLICATIONS = [
  {
    id: '1',
    name: 'Daily Offsite (tank/backup)',
    target: '192.168.20.5 (ssh)',
    status: 'idle',
    lastRun: '15m ago',
    progress: 0,
  },
  {
    id: '2',
    name: 'Hourly Sync (tank/projects)',
    target: '192.168.20.5 (ssh)',
    status: 'running',
    lastRun: 'Running...',
    progress: 45,
  },
]

export default function SnapshotReplication() {
  const [activeTab, setActiveTab] = useState<'snapshots' | 'replication' | 'restore'>('snapshots')
  const [searchQuery, setSearchQuery] = useState('')
  const [currentPage, setCurrentPage] = useState(1)
  const [showCreateReplication, setShowCreateReplication] = useState(false)
  const [showCreateSnapshot, setShowCreateSnapshot] = useState(false)
  const itemsPerPage = 10

  // Form state for replication
  const [replicationForm, setReplicationForm] = useState({
    name: '',
    sourceDataset: '',
    targetHost: '',
    targetDataset: '',
    targetPort: '22',
    targetUser: 'root',
    schedule: 'daily',
    scheduleTime: '00:00',
    compression: 'lz4',
    encryption: false,
    recursive: true,
    autoSnapshot: true,
  })

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

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

  // Fetch datasets for selected pool
  const fetchDatasets = async (poolName: string) => {
    try {
      const poolDatasets = await zfsApi.listDatasets(poolName)
      setDatasets((prev) => {
        const filtered = prev.filter((d) => d.pool !== poolName)
        return [...filtered, { pool: poolName, datasets: poolDatasets }]
      })
    } catch (error) {
      console.error('Failed to fetch datasets:', error)
    }
  }

  // Filter snapshots
  const filteredSnapshots = MOCK_SNAPSHOTS.filter((snapshot) => {
    const matchesSearch =
      snapshot.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      snapshot.dataset.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 = MOCK_SNAPSHOTS.length
  const totalReclaimable = MOCK_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 {
                    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' : '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('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
                <span className="ml-1 bg-[#2a3b4d] text-white text-[10px] px-1.5 py-0.5 rounded-full">
                  {MOCK_REPLICATIONS.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">
                  <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">
                    <Filter size={18} />
                    Dataset: All
                  </button>
                </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">
                      {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.name}</span>
                              {snapshot.isLatest && (
                                <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
                                className="p-1.5 hover:bg-[#2a3b4d] rounded text-text-secondary hover:text-white"
                                title="Rollback"
                              >
                                <RotateCcw size={20} />
                              </button>
                              <button
                                className="p-1.5 hover:bg-[#2a3b4d] rounded text-text-secondary hover:text-white"
                                title="Clone"
                              >
                                <Copy size={20} />
                              </button>
                              <button
                                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 === 'replication' && (
              <div className="p-6">
                <div className="flex justify-between items-center mb-4">
                  <h3 className="text-white text-lg font-bold">Replication Tasks</h3>
                  <button
                    onClick={() => 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>
                <div className="space-y-3">
                  {MOCK_REPLICATIONS.map((replication) => (
                    <div
                      key={replication.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 ${
                          replication.status === 'running'
                            ? 'bg-primary animate-pulse'
                            : 'bg-emerald-500 shadow-[0_0_8px_rgba(16,185,129,0.5)]'
                        }`}
                      ></div>
                      <div className="flex-1">
                        <p className="text-white text-sm font-medium">{replication.name}</p>
                        <p className="text-[#536b85] text-xs">Target: {replication.target}</p>
                        {replication.status === 'running' && (
                          <div className="w-full bg-[#2a3b4d] rounded-full h-1.5 mt-2">
                            <div
                              className="bg-primary h-1.5 rounded-full transition-all"
                              style={{ width: `${replication.progress}%` }}
                            ></div>
                          </div>
                        )}
                      </div>
                      <div className="text-right">
                        <p
                          className={`text-sm ${
                            replication.status === 'running' ? 'text-primary font-bold' : 'text-text-secondary'
                          }`}
                        >
                          {replication.status === 'running' ? `${replication.progress}%` : 'Idle'}
                        </p>
                        <p className="text-[#536b85] text-xs">{replication.lastRun}</p>
                      </div>
                      <button className="p-2 hover:bg-[#2a3b4d] rounded text-text-secondary hover:text-white transition-colors">
                        <MoreVertical size={18} />
                      </button>
                    </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">
                {MOCK_REPLICATIONS.map((replication) => (
                  <div
                    key={replication.id}
                    className="flex items-center gap-4 bg-[#111a22] p-3 rounded-lg border border-[#2a3b4d]"
                  >
                    <div
                      className={`w-2 h-2 rounded-full ${
                        replication.status === 'running'
                          ? 'bg-primary animate-pulse'
                          : 'bg-emerald-500 shadow-[0_0_8px_rgba(16,185,129,0.5)]'
                      }`}
                    ></div>
                    <div className="flex-1">
                      <p className="text-white text-sm font-medium">{replication.name}</p>
                      <p className="text-[#536b85] text-xs">Target: {replication.target}</p>
                      {replication.status === 'running' && (
                        <div className="w-full bg-[#2a3b4d] rounded-full h-1.5 mt-2">
                          <div
                            className="bg-primary h-1.5 rounded-full transition-all"
                            style={{ width: `${replication.progress}%` }}
                          ></div>
                        </div>
                      )}
                    </div>
                    <div className="text-right">
                      <p
                        className={`text-sm ${
                          replication.status === 'running' ? 'text-primary font-bold' : 'text-text-secondary'
                        }`}
                      >
                        {replication.status === 'running' ? `${replication.progress}%` : 'Idle'}
                      </p>
                      <p className="text-[#536b85] text-xs">{replication.lastRun}</p>
                    </div>
                  </div>
                ))}
              </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">Create Replication Task</h3>
              <button
                onClick={() => setShowCreateReplication(false)}
                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>

              {/* 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.sourceDataset}
                  onChange={(e) => {
                    setReplicationForm({ ...replicationForm, sourceDataset: e.target.value })
                    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 */}
              <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.targetHost}
                    onChange={(e) => setReplicationForm({ ...replicationForm, targetHost: e.target.value })}
                  />
                </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.targetPort}
                    onChange={(e) => setReplicationForm({ ...replicationForm, targetPort: e.target.value })}
                  />
                </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.targetUser}
                    onChange={(e) => setReplicationForm({ ...replicationForm, targetUser: e.target.value })}
                  />
                </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.targetDataset}
                    onChange={(e) => setReplicationForm({ ...replicationForm, targetDataset: e.target.value })}
                  />
                </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}
                    onChange={(e) => setReplicationForm({ ...replicationForm, schedule: e.target.value })}
                  >
                    <option value="hourly">Hourly</option>
                    <option value="daily">Daily</option>
                    <option value="weekly">Weekly</option>
                    <option value="monthly">Monthly</option>
                    <option value="custom">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.scheduleTime}
                    onChange={(e) => setReplicationForm({ ...replicationForm, scheduleTime: 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.autoSnapshot}
                    onChange={(e) => setReplicationForm({ ...replicationForm, autoSnapshot: 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={() => {
                    // TODO: Implement API call
                    console.log('Creating replication:', replicationForm)
                    alert('Replication task created successfully!')
                    setShowCreateReplication(false)
                    setReplicationForm({
                      name: '',
                      sourceDataset: '',
                      targetHost: '',
                      targetDataset: '',
                      targetPort: '22',
                      targetUser: 'root',
                      schedule: 'daily',
                      scheduleTime: '00:00',
                      compression: 'lz4',
                      encryption: false,
                      recursive: true,
                      autoSnapshot: true,
                    })
                  }}
                  className="px-4 h-10 bg-primary hover:bg-blue-600"
                >
                  <Save size={18} className="mr-2" />
                  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)}
        >
          <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)}
                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">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"
                />
              </div>
              <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">
                  <option value="">Select a dataset</option>
                </select>
              </div>
              <div className="flex justify-end gap-3 pt-4">
                <Button
                  onClick={() => setShowCreateSnapshot(false)}
                  variant="outline"
                  className="px-4 h-10 border-[#2a3b4d] text-white hover:bg-[#2a3b4d]"
                >
                  Cancel
                </Button>
                <Button
                  onClick={() => {
                    alert('Snapshot created successfully!')
                    setShowCreateSnapshot(false)
                  }}
                  className="px-4 h-10 bg-primary hover:bg-blue-600"
                >
                  Create Snapshot
                </Button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

