'use client';

/**
 * Manual Backup
 * Enterprise FinTech Platform — Backup & Restore System
 *
 * Super-Admin page to trigger a manual backup (database, files, or full)
 * immediately or schedule one for a future time.
 */

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { backupService } from '@/services/backup.service';
import type { BackupType, BackupScope } from '@/types/backup.types';

export default function ManualBackupPage() {
  const router = useRouter();
  const [type, setType] = useState<BackupType>('MANUAL');
  const [scope, setScope] = useState<BackupScope>('FULL');
  const [scheduledFor, setScheduledFor] = useState('');
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError(null);
    setResult(null);
    try {
      const res = await backupService.createBackup({
        type,
        scope,
        scheduledFor: scheduledFor ? new Date(scheduledFor).toISOString() : undefined,
      });
      setResult(
        `Backup created successfully. ID: ${res.backupId ?? 'pending'}. Status: ${res.status ?? 'PENDING'}`,
      );
      router.refresh();
    } catch (err: any) {
      setError(err?.response?.data?.message ?? 'Failed to create backup');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="max-w-2xl space-y-6 p-6">
      <div>
        <h1 className="text-2xl font-bold text-slate-100">Manual Backup</h1>
        <p className="text-sm text-slate-400">
          Create an on-demand backup or schedule one for a future time.
        </p>
      </div>

      <form onSubmit={handleSubmit} className="space-y-5 rounded-xl border border-white/10 bg-white/5 p-6">
        <div>
          <label className="mb-1 block text-sm text-slate-300">Backup Type</label>
          <select
            value={type}
            onChange={(e) => setType(e.target.value as BackupType)}
            className="w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm text-slate-100"
          >
            <option value="MANUAL">Manual</option>
            <option value="DAILY">Daily</option>
            <option value="WEEKLY">Weekly</option>
            <option value="MONTHLY">Monthly</option>
          </select>
        </div>

        <div>
          <label className="mb-1 block text-sm text-slate-300">Scope</label>
          <select
            value={scope}
            onChange={(e) => setScope(e.target.value as BackupScope)}
            className="w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm text-slate-100"
          >
            <option value="FULL">Full (Database + Files)</option>
            <option value="DATABASE_ONLY">Database Only</option>
            <option value="FILES_ONLY">Files Only</option>
          </select>
        </div>

        <div>
          <label className="mb-1 block text-sm text-slate-300">
            Schedule For (optional)
          </label>
          <input
            type="datetime-local"
            value={scheduledFor}
            onChange={(e) => setScheduledFor(e.target.value)}
            className="w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm text-slate-100"
          />
          <p className="mt-1 text-xs text-slate-500">
            Leave empty to run immediately.
          </p>
        </div>

        {error && (
          <div className="rounded-lg border border-red-500/30 bg-red-500/10 p-3 text-sm text-red-300">
            {error}
          </div>
        )}
        {result && (
          <div className="rounded-lg border border-emerald-500/30 bg-emerald-500/10 p-3 text-sm text-emerald-300">
            {result}
          </div>
        )}

        <button
          type="submit"
          disabled={loading}
          className="rounded-lg bg-cyan-600 px-4 py-2 text-sm font-semibold text-white hover:bg-cyan-500 disabled:opacity-50"
        >
          {loading ? 'Creating…' : 'Create Backup'}
        </button>
      </form>
    </div>
  );
}
