'use client';

/**
 * Backup History
 * Enterprise FinTech Platform — Backup & Restore System
 *
 * Super-Admin table of all backups with filters, pagination, and the
 * ability to verify, restore, or delete individual backups.
 */

import { useEffect, useState } from 'react';
import { backupService } from '@/services/backup.service';
import type { BackupHistoryItem } from '@/types/backup.types';

export default function BackupHistoryPage() {
  const [items, setItems] = useState<BackupHistoryItem[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [limit] = useState(20);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [typeFilter, setTypeFilter] = useState('');
  const [statusFilter, setStatusFilter] = useState('');

  const load = async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await backupService.getHistory({
        page,
        limit,
        type: typeFilter || undefined,
        status: statusFilter || undefined,
      });
      // Defensive: exclude DELETED backups when the user hasn't explicitly
      // filtered for them (the backend should already do this, but we guard
      // against stale backend responses).
      const shouldExcludeDeleted = !statusFilter || statusFilter !== 'DELETED';
      const filtered = shouldExcludeDeleted
        ? (res.items ?? []).filter((b) => b.status !== 'DELETED')
        : (res.items ?? []);
      setItems(filtered);
      setTotal(res.total ?? 0);
    } catch (err: any) {
      setError(err?.response?.data?.message ?? 'Failed to load backup history');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    load();
  }, [page, typeFilter, statusFilter]);

  const handleVerify = async (id: string) => {
    try {
      await backupService.verifyBackup(id);
      load();
    } catch (err: any) {
      alert(err?.response?.data?.message ?? 'Verification failed');
    }
  };

  const handleDelete = async (id: string) => {
    if (!confirm('Delete this backup? This cannot be undone.')) return;
    try {
      await backupService.deleteBackup(id);
      setItems((prev) => prev.filter((b) => b.id !== id));
      setTotal((prev) => Math.max(0, prev - 1));
    } catch (err: any) {
      alert(err?.response?.data?.message ?? 'Delete failed');
    }
  };

  const fmtBytes = (bytes?: string) => {
    const n = Number(bytes ?? 0);
    if (!n) return '—';
    const units = ['B', 'KB', 'MB', 'GB', 'TB'];
    let i = 0;
    let v = n;
    while (v >= 1024 && i < units.length - 1) {
      v /= 1024;
      i++;
    }
    return `${v.toFixed(1)} ${units[i]}`;
  };

  const statusColor = (s: string) => {
    switch (s) {
      case 'COMPLETED':
        return 'bg-emerald-500/20 text-emerald-300';
      case 'FAILED':
        return 'bg-red-500/20 text-red-300';
      case 'RUNNING':
      case 'VERIFYING':
      case 'COMPRESSING':
      case 'PENDING':
        return 'bg-amber-500/20 text-amber-300';
      default:
        return 'bg-slate-500/20 text-slate-300';
    }
  };

  return (
    <div className="space-y-6 p-6">
      <div>
        <h1 className="text-2xl font-bold text-slate-100">Backup History</h1>
        <p className="text-sm text-slate-400">
          All backup runs, scheduled and manual ({total} total)
        </p>
      </div>

      <div className="flex flex-wrap gap-3">
        <select
          value={typeFilter}
          onChange={(e) => {
            setTypeFilter(e.target.value);
            setPage(1);
          }}
          className="rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm text-slate-100"
        >
          <option value="">All Types</option>
          <option value="DAILY">Daily</option>
          <option value="WEEKLY">Weekly</option>
          <option value="MONTHLY">Monthly</option>
          <option value="MANUAL">Manual</option>
        </select>
        <select
          value={statusFilter}
          onChange={(e) => {
            setStatusFilter(e.target.value);
            setPage(1);
          }}
          className="rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm text-slate-100"
        >
          <option value="">All Statuses</option>
          <option value="COMPLETED">Completed</option>
          <option value="FAILED">Failed</option>
          <option value="RUNNING">Running</option>
          <option value="EXPIRED">Expired</option>
          <option value="DELETED">Deleted</option>
        </select>
      </div>

      {error && (
        <div className="rounded-lg border border-red-500/30 bg-red-500/10 p-4 text-sm text-red-300">
          {error}
        </div>
      )}

      {loading ? (
        <div className="text-slate-400">Loading…</div>
      ) : (
        <div className="overflow-x-auto rounded-xl border border-white/10 bg-white/5">
          <table className="w-full text-left text-sm">
            <thead className="border-b border-white/10 text-xs uppercase text-slate-400">
              <tr>
                <th className="px-4 py-3">Type</th>
                <th className="px-4 py-3">Scope</th>
                <th className="px-4 py-3">Status</th>
                <th className="px-4 py-3">Created</th>
                <th className="px-4 py-3">Size</th>
                <th className="px-4 py-3">Encrypted</th>
                <th className="px-4 py-3">Actions</th>
              </tr>
            </thead>
            <tbody>
              {items.length === 0 ? (
                <tr>
                  <td colSpan={7} className="px-4 py-6 text-center text-slate-500">
                    No backups found
                  </td>
                </tr>
              ) : (
                items.map((b) => (
                  <tr key={b.id} className="border-b border-white/5">
                    <td className="px-4 py-3 capitalize text-slate-200">{b.type.toLowerCase()}</td>
                    <td className="px-4 py-3 text-slate-400">{b.scope}</td>
                    <td className="px-4 py-3">
                      <span className={`rounded-full px-2 py-1 text-xs ${statusColor(b.status)}`}>
                        {b.status}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-slate-400">
                      {new Date(b.createdAt).toLocaleString()}
                    </td>
                    <td className="px-4 py-3 font-mono text-slate-300">
                      {fmtBytes(b.fileSizeBytes)}
                    </td>
                    <td className="px-4 py-3 text-slate-400">
                      {b.isEncrypted ? `Yes (${b.encryptionAlgorithm ?? 'AES-256-GCM'})` : 'No'}
                    </td>
                    <td className="px-4 py-3">
                      <div className="flex gap-2">
                        <button
                          onClick={() => handleVerify(b.id)}
                          className="rounded bg-cyan-600 px-2 py-1 text-xs text-white hover:bg-cyan-500"
                        >
                          Verify
                        </button>
                        <a
                          href={`/super-admin/backup/restore?backupId=${b.id}`}
                          className="rounded bg-emerald-600 px-2 py-1 text-xs text-white hover:bg-emerald-500"
                        >
                          Restore
                        </a>
                        <button
                          onClick={() => handleDelete(b.id)}
                          className="rounded bg-red-600 px-2 py-1 text-xs text-white hover:bg-red-500"
                        >
                          Delete
                        </button>
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      )}

      {total > limit && (
        <div className="flex items-center justify-between">
          <button
            onClick={() => setPage((p) => Math.max(1, p - 1))}
            disabled={page <= 1}
            className="rounded-lg border border-white/10 px-3 py-2 text-sm text-slate-200 disabled:opacity-50"
          >
            Prev
          </button>
          <span className="text-sm text-slate-400">
            Page {page} of {Math.max(1, Math.ceil(total / limit))}
          </span>
          <button
            onClick={() => setPage((p) => p + 1)}
            disabled={page >= Math.ceil(total / limit)}
            className="rounded-lg border border-white/10 px-3 py-2 text-sm text-slate-200 disabled:opacity-50"
          >
            Next
          </button>
        </div>
      )}
    </div>
  );
}
