"use client";

import { useState, useEffect } from "react";
import {
  HardDrive,
  Activity,
  Play,
  Plus,
  Trash2,
  CheckCircle,
  XCircle,
  Clock,
  Loader2,
} from "lucide-react";
import { useBackupService } from "@/hooks/useBackupService";

const BACKUP_TYPES = [
  { id: "full", label: "Full" },
  { id: "incremental", label: "Incremental" },
  { id: "differential", label: "Differential" },
] as const;

const SCHEDULE_PRESETS = [
  { id: "disabled", label: "Disabled" },
  { id: "hourly", label: "Hourly" },
  { id: "daily", label: "Daily" },
  { id: "weekly", label: "Weekly" },
  { id: "monthly", label: "Monthly" },
] as const;

const DEST_TYPES = [
  { id: "local", label: "Local / USB" },
  { id: "sftp", label: "SFTP / NAS" },
  { id: "nas", label: "Finder Share" },
  { id: "iscsi", label: "iSCSI" },
] as const;

function formatBytes(bytes: number): string {
  if (bytes === 0) return "0 B";
  const k = 1024;
  const sizes = ["B", "KB", "MB", "GB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return `${(bytes / Math.pow(k, i)).toFixed(1)} ${sizes[i]}`;
}

function formatDate(iso: string): string {
  return new Date(iso).toLocaleString();
}

export function BackupView() {
  const {
    health,
    settings,
    status,
    history,
    destinations,
    volumes,
    loading,
    updateSettings,
    runBackup,
    addDestination,
    removeDestination,
    testDestination,
  } = useBackupService();

  const [backupType, setBackupType] = useState<"full" | "incremental" | "differential">("full");
  const [backupDestId, setBackupDestId] = useState("");
  const [showAddDest, setShowAddDest] = useState(false);
  const [newDest, setNewDest] = useState({ name: "", type: "local" as string, config: {} as Record<string, unknown> });
  const [testResult, setTestResult] = useState<{ success: boolean; message: string } | null>(null);
  const [testing, setTesting] = useState<string | null>(null);

  // Sync backupDestId default from settings
  useEffect(() => {
    if (settings?.defaultDestinationId && !backupDestId) {
      setBackupDestId(settings.defaultDestinationId);
    }
  }, [settings?.defaultDestinationId, backupDestId]);

  if (loading) {
    return (
      <div className="flex h-full items-center justify-center">
        <p className="text-sm text-zinc-400">Loading backup settings...</p>
      </div>
    );
  }

  const isOnline = health?.status === "online";
  const isRunning = status?.state === "running";

  const handleRunBackup = async () => {
    if (isRunning) return;
    await runBackup({ backupType, destinationId: backupDestId || undefined });
  };

  const handleTestDestination = async (id: string) => {
    setTesting(id);
    setTestResult(null);
    const result = await testDestination(id);
    setTestResult(result);
    setTesting(null);
  };

  const handleAddDestination = async () => {
    if (!newDest.name.trim()) return;
    await addDestination({
      name: newDest.name.trim(),
      type: newDest.type as "local" | "nas" | "sftp" | "iscsi",
      config: newDest.config as never,
    });
    setNewDest({ name: "", type: "local", config: {} });
    setShowAddDest(false);
  };

  const schedule = settings?.schedule;
  const retention = settings?.retention;

  const inputClass =
    "rounded-md border border-zinc-300 bg-white px-2 py-1.5 text-sm text-zinc-900 placeholder-zinc-400 dark:border-zinc-600 dark:bg-zinc-800 dark:text-zinc-100";
  const selectClass =
    "rounded-md border border-zinc-300 bg-white px-2 py-1.5 text-sm text-zinc-900 dark:border-zinc-600 dark:bg-zinc-800 dark:text-zinc-100";

  return (
    <div className="h-full overflow-y-auto p-6">
      <div className="mx-auto max-w-2xl space-y-6">
        {/* Header */}
        <div className="flex items-center gap-3">
          <HardDrive size={24} className="text-zinc-600 dark:text-zinc-400" />
          <h1 className="text-xl font-semibold text-zinc-900 dark:text-zinc-100">
            Backup Administration
          </h1>
        </div>

        {/* 1. Service Status */}
        <div className="rounded-lg border border-zinc-200 p-4 dark:border-zinc-700">
          <div className="flex items-center gap-2">
            <Activity size={16} className="text-zinc-500" />
            <h2 className="text-sm font-medium text-zinc-700 dark:text-zinc-300">
              Service Status
            </h2>
          </div>

          <div className="mt-3 flex items-center gap-2">
            <span
              className={`h-2 w-2 rounded-full ${isOnline ? "bg-green-500" : "bg-red-500"}`}
            />
            <span className="text-sm text-zinc-600 dark:text-zinc-400">
              {isOnline ? "Online" : "Offline"}
            </span>
            {isRunning && (
              <span className="ml-2 flex items-center gap-1 text-xs text-blue-500">
                <Loader2 size={12} className="animate-spin" />
                Backup running…
              </span>
            )}
          </div>

          {health && (
            <div className="mt-3 grid grid-cols-2 gap-x-6 gap-y-1">
              <div>
                <span className="text-xs text-zinc-400 dark:text-zinc-500">Last backup</span>
                <p className="text-sm text-zinc-700 dark:text-zinc-300">
                  {health.lastBackup ? formatDate(health.lastBackup.timestamp) : "—"}
                </p>
              </div>
              <div>
                <span className="text-xs text-zinc-400 dark:text-zinc-500">Next scheduled</span>
                <p className="text-sm text-zinc-700 dark:text-zinc-300">
                  {health.nextScheduledBackup ? formatDate(health.nextScheduledBackup) : "—"}
                </p>
              </div>
              {health.lastBackup && (
                <>
                  <div>
                    <span className="text-xs text-zinc-400 dark:text-zinc-500">Last size</span>
                    <p className="text-sm text-zinc-700 dark:text-zinc-300">
                      {formatBytes(health.lastBackup.sizeBytes)}
                    </p>
                  </div>
                  <div>
                    <span className="text-xs text-zinc-400 dark:text-zinc-500">Last status</span>
                    <p
                      className={`text-sm ${
                        health.lastBackup.status === "completed"
                          ? "text-green-600 dark:text-green-400"
                          : "text-red-600 dark:text-red-400"
                      }`}
                    >
                      {health.lastBackup.status}
                    </p>
                  </div>
                </>
              )}
            </div>
          )}
        </div>

        {/* 2. Backup Now */}
        <div className="rounded-lg border border-zinc-200 p-4 dark:border-zinc-700">
          <div className="flex items-center gap-2">
            <Play size={16} className="text-zinc-500" />
            <h2 className="text-sm font-medium text-zinc-700 dark:text-zinc-300">
              Backup Now
            </h2>
          </div>

          <div className="mt-3 flex flex-wrap items-end gap-3">
            <div className="flex flex-col gap-1">
              <label className="text-xs text-zinc-500 dark:text-zinc-400">Backup type</label>
              <select
                value={backupType}
                onChange={(e) => setBackupType(e.target.value as typeof backupType)}
                disabled={isRunning}
                className={selectClass}
              >
                {BACKUP_TYPES.map((t) => (
                  <option key={t.id} value={t.id}>
                    {t.label}
                  </option>
                ))}
              </select>
            </div>

            <div className="flex flex-col gap-1">
              <label className="text-xs text-zinc-500 dark:text-zinc-400">Destination</label>
              <select
                value={backupDestId}
                onChange={(e) => setBackupDestId(e.target.value)}
                disabled={isRunning || destinations.length === 0}
                className={selectClass}
              >
                {destinations.length === 0 ? (
                  <option value="">No destinations</option>
                ) : (
                  destinations.map((d) => (
                    <option key={d.id} value={d.id}>
                      {d.name}
                    </option>
                  ))
                )}
              </select>
            </div>

            <button
              onClick={handleRunBackup}
              disabled={isRunning || destinations.length === 0}
              className="flex items-center gap-1.5 rounded-md border border-zinc-900 bg-zinc-900 px-3 py-1.5 text-sm text-white transition-colors hover:bg-zinc-700 disabled:opacity-50 dark:border-zinc-100 dark:bg-zinc-100 dark:text-zinc-900 dark:hover:bg-zinc-300"
            >
              {isRunning ? (
                <Loader2 size={14} className="animate-spin" />
              ) : (
                <Play size={14} />
              )}
              {isRunning ? "Running…" : "Run Backup"}
            </button>
          </div>
        </div>

        {/* 3. Destinations */}
        <div className="rounded-lg border border-zinc-200 p-4 dark:border-zinc-700">
          <div className="flex items-center justify-between">
            <h2 className="text-sm font-medium text-zinc-700 dark:text-zinc-300">
              Destinations
            </h2>
            <button
              onClick={() => {
                setShowAddDest((v) => !v);
                setTestResult(null);
              }}
              className="flex items-center gap-1 rounded-md border border-zinc-300 px-2 py-1 text-xs text-zinc-600 transition-colors hover:border-zinc-400 dark:border-zinc-600 dark:text-zinc-400 dark:hover:border-zinc-500"
            >
              <Plus size={12} />
              Add
            </button>
          </div>

          <div className="mt-3 space-y-2">
            {destinations.length === 0 && (
              <p className="text-xs text-zinc-400">No destinations configured.</p>
            )}
            {destinations.map((dest) => (
              <div
                key={dest.id}
                className="flex items-center justify-between rounded-md bg-zinc-50 px-3 py-2 dark:bg-zinc-800"
              >
                <div>
                  <span className="text-sm font-medium text-zinc-800 dark:text-zinc-200">
                    {dest.name}
                  </span>
                  <span className="ml-2 text-xs text-zinc-400">{dest.type}</span>
                </div>
                <div className="flex items-center gap-2">
                  <button
                    onClick={() => handleTestDestination(dest.id)}
                    disabled={testing === dest.id}
                    className="text-xs text-zinc-500 transition-colors hover:text-zinc-700 disabled:opacity-50 dark:text-zinc-400 dark:hover:text-zinc-200"
                  >
                    {testing === dest.id ? (
                      <Loader2 size={13} className="animate-spin" />
                    ) : (
                      "Test"
                    )}
                  </button>
                  <button
                    onClick={() => removeDestination(dest.id)}
                    className="text-zinc-400 transition-colors hover:text-red-500"
                  >
                    <Trash2 size={14} />
                  </button>
                </div>
              </div>
            ))}

            {testResult && (
              <div
                className={`flex items-center gap-1.5 rounded-md px-3 py-2 text-xs ${
                  testResult.success
                    ? "bg-green-50 text-green-700 dark:bg-green-950 dark:text-green-300"
                    : "bg-red-50 text-red-700 dark:bg-red-950 dark:text-red-300"
                }`}
              >
                {testResult.success ? (
                  <CheckCircle size={13} />
                ) : (
                  <XCircle size={13} />
                )}
                {testResult.message}
              </div>
            )}
          </div>

          {/* Add destination form */}
          {showAddDest && (
            <div className="mt-4 space-y-3 border-t border-zinc-200 pt-4 dark:border-zinc-700">
              <div className="flex gap-2">
                <div className="flex flex-1 flex-col gap-1">
                  <label className="text-xs text-zinc-500 dark:text-zinc-400">Name</label>
                  <input
                    type="text"
                    placeholder="My Backup Drive"
                    value={newDest.name}
                    onChange={(e) => setNewDest((d) => ({ ...d, name: e.target.value }))}
                    className={`${inputClass} w-full`}
                  />
                </div>
                <div className="flex flex-col gap-1">
                  <label className="text-xs text-zinc-500 dark:text-zinc-400">Type</label>
                  <select
                    value={newDest.type}
                    onChange={(e) =>
                      setNewDest((d) => ({ ...d, type: e.target.value, config: {} }))
                    }
                    className={selectClass}
                  >
                    {DEST_TYPES.map((t) => (
                      <option key={t.id} value={t.id}>
                        {t.label}
                      </option>
                    ))}
                  </select>
                </div>
              </div>

              {/* Dynamic config fields */}
              {newDest.type === "local" && (
                <div className="flex flex-col gap-1">
                  <label className="text-xs text-zinc-500 dark:text-zinc-400">Backup folder path</label>
                  <input
                    type="text"
                    placeholder="/Volumes/MyDrive/teletraan-backups"
                    value={(newDest.config as { path?: string }).path ?? ""}
                    onChange={(e) =>
                      setNewDest((d) => ({ ...d, config: { ...d.config, path: e.target.value } }))
                    }
                    className={`${inputClass} w-full`}
                  />
                  <p className="text-xs text-zinc-400">The folder will be created automatically if it doesn't exist.</p>
                </div>
              )}

              {newDest.type === "sftp" && (
                <div className="space-y-2">
                  <div className="flex gap-2">
                    <div className="flex flex-1 flex-col gap-1">
                      <label className="text-xs text-zinc-500 dark:text-zinc-400">Host</label>
                      <input
                        type="text"
                        placeholder="backup.example.com"
                        value={(newDest.config as { host?: string }).host ?? ""}
                        onChange={(e) =>
                          setNewDest((d) => ({ ...d, config: { ...d.config, host: e.target.value } }))
                        }
                        className={`${inputClass} w-full`}
                      />
                    </div>
                    <div className="flex flex-col gap-1">
                      <label className="text-xs text-zinc-500 dark:text-zinc-400">Port</label>
                      <input
                        type="number"
                        placeholder="22"
                        value={(newDest.config as { port?: number }).port ?? ""}
                        onChange={(e) =>
                          setNewDest((d) => ({
                            ...d,
                            config: { ...d.config, port: Number(e.target.value) },
                          }))
                        }
                        className={`${inputClass} w-20`}
                      />
                    </div>
                  </div>
                  <div className="flex gap-2">
                    <div className="flex flex-1 flex-col gap-1">
                      <label className="text-xs text-zinc-500 dark:text-zinc-400">Username</label>
                      <input
                        type="text"
                        placeholder="user"
                        value={(newDest.config as { username?: string }).username ?? ""}
                        onChange={(e) =>
                          setNewDest((d) => ({
                            ...d,
                            config: { ...d.config, username: e.target.value },
                          }))
                        }
                        className={`${inputClass} w-full`}
                      />
                    </div>
                    <div className="flex flex-col gap-1">
                      <label className="text-xs text-zinc-500 dark:text-zinc-400">Auth method</label>
                      <select
                        value={(newDest.config as { authMethod?: string }).authMethod ?? "key"}
                        onChange={(e) =>
                          setNewDest((d) => ({
                            ...d,
                            config: { ...d.config, authMethod: e.target.value },
                          }))
                        }
                        className={selectClass}
                      >
                        <option value="key">SSH Key</option>
                        <option value="password">Password</option>
                      </select>
                    </div>
                  </div>
                  {(newDest.config as { authMethod?: string }).authMethod === "password" ? (
                    <div className="flex flex-col gap-1">
                      <label className="text-xs text-zinc-500 dark:text-zinc-400">Password</label>
                      <input
                        type="password"
                        placeholder="••••••••"
                        value={(newDest.config as { password?: string }).password ?? ""}
                        onChange={(e) =>
                          setNewDest((d) => ({
                            ...d,
                            config: { ...d.config, password: e.target.value },
                          }))
                        }
                        className={`${inputClass} w-full`}
                      />
                    </div>
                  ) : (
                    <div className="flex flex-col gap-1">
                      <label className="text-xs text-zinc-500 dark:text-zinc-400">Key path</label>
                      <input
                        type="text"
                        placeholder="~/.ssh/id_rsa"
                        value={(newDest.config as { keyPath?: string }).keyPath ?? ""}
                        onChange={(e) =>
                          setNewDest((d) => ({
                            ...d,
                            config: { ...d.config, keyPath: e.target.value },
                          }))
                        }
                        className={`${inputClass} w-full`}
                      />
                    </div>
                  )}
                  <div className="flex flex-col gap-1">
                    <label className="text-xs text-zinc-500 dark:text-zinc-400">Remote path</label>
                    <input
                      type="text"
                      placeholder="/backups"
                      value={(newDest.config as { remotePath?: string }).remotePath ?? ""}
                      onChange={(e) =>
                        setNewDest((d) => ({
                          ...d,
                          config: { ...d.config, remotePath: e.target.value },
                        }))
                      }
                      className={`${inputClass} w-full`}
                    />
                  </div>
                </div>
              )}

              {newDest.type === "nas" && (
                <div className="space-y-2">
                  {volumes.length > 0 ? (
                    <div className="flex flex-col gap-1">
                      <label className="text-xs text-zinc-500 dark:text-zinc-400">Select a mounted share</label>
                      <select
                        value={(newDest.config as { mountPoint?: string }).mountPoint ?? ""}
                        onChange={(e) => {
                          const vol = volumes.find((v) => v.path === e.target.value);
                          setNewDest((d) => ({
                            ...d,
                            name: d.name || vol?.name || "",
                            config: { ...d.config, sharePath: vol?.path ?? "", mountPoint: e.target.value, protocol: "smb" },
                          }));
                        }}
                        className={selectClass}
                      >
                        <option value="">Choose a volume...</option>
                        {volumes.map((v) => (
                          <option key={v.path} value={v.path}>{v.name} ({v.path})</option>
                        ))}
                      </select>
                    </div>
                  ) : (
                    <div className="rounded-md bg-amber-50 p-3 dark:bg-amber-900/20">
                      <p className="text-xs text-amber-700 dark:text-amber-400">
                        No network shares detected. Connect to your NAS in Finder first (Go &gt; Connect to Server), then refresh this page.
                      </p>
                    </div>
                  )}
                  <p className="text-xs text-zinc-400">
                    Uses a share already mounted in Finder. For automatic headless connections, use SFTP / NAS instead.
                  </p>
                </div>
              )}

              {newDest.type === "iscsi" && (
                <div className="space-y-2">
                  <div className="flex flex-col gap-1">
                    <label className="text-xs text-zinc-500 dark:text-zinc-400">Target IQN</label>
                    <input
                      type="text"
                      placeholder="iqn.2001-04.com.example:storage.target"
                      value={(newDest.config as { targetIqn?: string }).targetIqn ?? ""}
                      onChange={(e) =>
                        setNewDest((d) => ({
                          ...d,
                          config: { ...d.config, targetIqn: e.target.value },
                        }))
                      }
                      className={`${inputClass} w-full`}
                    />
                  </div>
                  <div className="flex gap-2">
                    <div className="flex flex-1 flex-col gap-1">
                      <label className="text-xs text-zinc-500 dark:text-zinc-400">Portal address</label>
                      <input
                        type="text"
                        placeholder="192.168.1.100"
                        value={(newDest.config as { portalAddress?: string }).portalAddress ?? ""}
                        onChange={(e) =>
                          setNewDest((d) => ({
                            ...d,
                            config: { ...d.config, portalAddress: e.target.value },
                          }))
                        }
                        className={`${inputClass} w-full`}
                      />
                    </div>
                    <div className="flex flex-col gap-1">
                      <label className="text-xs text-zinc-500 dark:text-zinc-400">Port</label>
                      <input
                        type="number"
                        placeholder="3260"
                        value={(newDest.config as { port?: number }).port ?? ""}
                        onChange={(e) =>
                          setNewDest((d) => ({
                            ...d,
                            config: { ...d.config, port: Number(e.target.value) },
                          }))
                        }
                        className={`${inputClass} w-20`}
                      />
                    </div>
                  </div>
                  <p className="text-xs text-zinc-400">The target will be mounted automatically when connecting.</p>
                </div>
              )}

              <div className="flex justify-end gap-2">
                <button
                  onClick={() => {
                    setShowAddDest(false);
                    setNewDest({ name: "", type: "local", config: {} });
                  }}
                  className="rounded-md border border-zinc-300 px-3 py-1.5 text-sm text-zinc-600 transition-colors hover:border-zinc-400 dark:border-zinc-600 dark:text-zinc-400 dark:hover:border-zinc-500"
                >
                  Cancel
                </button>
                <button
                  onClick={handleAddDestination}
                  disabled={!newDest.name.trim()}
                  className="flex items-center gap-1 rounded-md border border-zinc-900 bg-zinc-900 px-3 py-1.5 text-sm text-white transition-colors hover:bg-zinc-700 disabled:opacity-50 dark:border-zinc-100 dark:bg-zinc-100 dark:text-zinc-900 dark:hover:bg-zinc-300"
                >
                  <Plus size={14} />
                  Save Destination
                </button>
              </div>
            </div>
          )}
        </div>

        {/* 4. Schedule */}
        <div className="rounded-lg border border-zinc-200 p-4 dark:border-zinc-700">
          <div className="flex items-center gap-2">
            <Clock size={16} className="text-zinc-500" />
            <h2 className="text-sm font-medium text-zinc-700 dark:text-zinc-300">Schedule</h2>
          </div>

          <div className="mt-3">
            <label className="text-xs text-zinc-500 dark:text-zinc-400">Preset</label>
            <div className="mt-1.5 flex flex-wrap gap-2">
              {SCHEDULE_PRESETS.map((preset) => (
                <button
                  key={preset.id}
                  onClick={() =>
                    updateSettings({
                      schedule: { ...schedule!, preset: preset.id as "disabled" | "hourly" | "daily" | "weekly" | "monthly" },
                    })
                  }
                  className={`rounded-md border px-3 py-1.5 text-sm transition-colors ${
                    schedule?.preset === preset.id
                      ? "border-zinc-900 bg-zinc-900 text-white dark:border-zinc-100 dark:bg-zinc-100 dark:text-zinc-900"
                      : "border-zinc-300 text-zinc-600 hover:border-zinc-400 dark:border-zinc-600 dark:text-zinc-400 dark:hover:border-zinc-500"
                  }`}
                >
                  {preset.label}
                </button>
              ))}
            </div>
          </div>

          {schedule?.preset !== "disabled" && (
            <div className="mt-4 space-y-3">
              <div className="flex flex-wrap gap-3">
                <div className="flex flex-col gap-1">
                  <label className="text-xs text-zinc-500 dark:text-zinc-400">Time</label>
                  <input
                    type="time"
                    value={schedule?.time ?? "02:00"}
                    onChange={(e) =>
                      updateSettings({ schedule: { ...schedule!, time: e.target.value } })
                    }
                    className={inputClass}
                  />
                </div>

                {schedule?.preset === "weekly" && (
                  <div className="flex flex-col gap-1">
                    <label className="text-xs text-zinc-500 dark:text-zinc-400">Day of week</label>
                    <select
                      value={schedule?.dayOfWeek ?? 0}
                      onChange={(e) =>
                        updateSettings({
                          schedule: { ...schedule!, dayOfWeek: Number(e.target.value) },
                        })
                      }
                      className={selectClass}
                    >
                      {["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"].map(
                        (day, i) => (
                          <option key={day} value={i}>
                            {day}
                          </option>
                        )
                      )}
                    </select>
                  </div>
                )}

                {schedule?.preset === "monthly" && (
                  <div className="flex flex-col gap-1">
                    <label className="text-xs text-zinc-500 dark:text-zinc-400">Day of month</label>
                    <input
                      type="number"
                      min={1}
                      max={28}
                      value={schedule?.dayOfMonth ?? 1}
                      onChange={(e) =>
                        updateSettings({
                          schedule: { ...schedule!, dayOfMonth: Number(e.target.value) },
                        })
                      }
                      className={`${inputClass} w-20`}
                    />
                  </div>
                )}
              </div>

              <div className="flex flex-wrap gap-3">
                <div className="flex flex-col gap-1">
                  <label className="text-xs text-zinc-500 dark:text-zinc-400">Backup type</label>
                  <select
                    value={schedule?.backupType ?? "full"}
                    onChange={(e) =>
                      updateSettings({
                        schedule: {
                          ...schedule!,
                          backupType: e.target.value as "full" | "incremental" | "differential",
                        },
                      })
                    }
                    className={selectClass}
                  >
                    {BACKUP_TYPES.map((t) => (
                      <option key={t.id} value={t.id}>
                        {t.label}
                      </option>
                    ))}
                  </select>
                </div>

                <div className="flex flex-col gap-1">
                  <label className="text-xs text-zinc-500 dark:text-zinc-400">Destination</label>
                  <select
                    value={schedule?.destinationId ?? ""}
                    onChange={(e) =>
                      updateSettings({
                        schedule: { ...schedule!, destinationId: e.target.value },
                      })
                    }
                    disabled={destinations.length === 0}
                    className={selectClass}
                  >
                    {destinations.length === 0 ? (
                      <option value="">No destinations</option>
                    ) : (
                      destinations.map((d) => (
                        <option key={d.id} value={d.id}>
                          {d.name}
                        </option>
                      ))
                    )}
                  </select>
                </div>
              </div>
            </div>
          )}
        </div>

        {/* 5. Retention Policy */}
        <div className="rounded-lg border border-zinc-200 p-4 dark:border-zinc-700">
          <h2 className="text-sm font-medium text-zinc-700 dark:text-zinc-300">
            Retention Policy
          </h2>
          <p className="mt-1 text-xs text-zinc-400">
            Number of backups to keep per interval.
          </p>

          <div className="mt-3 flex flex-wrap gap-4">
            <div className="flex flex-col gap-1">
              <label className="text-xs text-zinc-500 dark:text-zinc-400">Daily</label>
              <input
                type="number"
                min={0}
                value={retention?.dailyCount ?? 7}
                onChange={(e) =>
                  updateSettings({
                    retention: { ...retention!, dailyCount: Number(e.target.value) },
                  })
                }
                className={`${inputClass} w-20`}
              />
            </div>
            <div className="flex flex-col gap-1">
              <label className="text-xs text-zinc-500 dark:text-zinc-400">Weekly</label>
              <input
                type="number"
                min={0}
                value={retention?.weeklyCount ?? 4}
                onChange={(e) =>
                  updateSettings({
                    retention: { ...retention!, weeklyCount: Number(e.target.value) },
                  })
                }
                className={`${inputClass} w-20`}
              />
            </div>
            <div className="flex flex-col gap-1">
              <label className="text-xs text-zinc-500 dark:text-zinc-400">Monthly</label>
              <input
                type="number"
                min={0}
                value={retention?.monthlyCount ?? 12}
                onChange={(e) =>
                  updateSettings({
                    retention: { ...retention!, monthlyCount: Number(e.target.value) },
                  })
                }
                className={`${inputClass} w-20`}
              />
            </div>
          </div>
        </div>

        {/* 6. Backup History */}
        <div className="rounded-lg border border-zinc-200 p-4 dark:border-zinc-700">
          <h2 className="text-sm font-medium text-zinc-700 dark:text-zinc-300">
            Backup History
          </h2>

          <div className="mt-3 max-h-64 space-y-2 overflow-y-auto">
            {history.length === 0 && (
              <p className="text-xs text-zinc-400">No backups recorded yet.</p>
            )}
            {history.map((entry) => {
              const destName =
                destinations.find((d) => d.id === entry.destination)?.name ?? entry.destination;
              return (
                <div
                  key={entry.id}
                  className="flex items-start justify-between rounded-md bg-zinc-50 px-3 py-2 dark:bg-zinc-800"
                >
                  <div className="flex items-start gap-2">
                    {entry.status === "completed" ? (
                      <CheckCircle size={15} className="mt-0.5 shrink-0 text-green-500" />
                    ) : (
                      <XCircle size={15} className="mt-0.5 shrink-0 text-red-500" />
                    )}
                    <div>
                      <div className="flex items-center gap-2">
                        <span className="text-sm font-medium capitalize text-zinc-800 dark:text-zinc-200">
                          {entry.type}
                        </span>
                        <span className="text-xs text-zinc-400">{destName}</span>
                      </div>
                      <div className="mt-0.5 text-xs text-zinc-400">
                        {formatDate(entry.timestamp)} · {formatBytes(entry.sizeBytes)} ·{" "}
                        {entry.fileCount.toLocaleString()} files
                      </div>
                      {entry.error && (
                        <div className="mt-0.5 text-xs text-red-500">{entry.error}</div>
                      )}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
}
