'use client';
import { useEffect, useState, useCallback } from 'react';
import { backupService } from '@/services/backup.service';
import type { BackupHistoryItem, BackupType } from '@/types/backup.types';

const STATUS_STYLES: Record<string, string> = {
  COMPLETED: 'bg-emerald-500/15 text-emerald-400 border-emerald-500/20',
  RUNNING: 'bg-blue-500/15 text-blue-400 border-blue-500/20',
  FAILED: 'bg-red-500/15 text-red-400 border-red-500/20',
  PENDING: 'bg-amber-500/15 text-amber-400 border-amber-500/20',
  VERIFYING: 'bg-purple-500/15 text-purple-400 border-purple-500/20',
  COMPRESSING: 'bg-cyan-500/15 text-cyan-400 border-cyan-500/20',
  EXPIRED: 'bg-slate-500/15 text-slate-400 border-slate-500/20',
  DELETED: 'bg-slate-500/15 text-slate-400 border-slate-500/20',
};

function formatBytes(bytesStr?: string): string {
  if (!bytesStr) return '0 B';
  const bytes = Number(bytesStr);
  if (bytes === 0) return '0 B';
  const units = ['B', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(1024));
  return `${(bytes / Math.pow(1024, i)).toFixed(2)} ${units[i]}`;
}

function formatDate(d?: string): string {
  if (!d) return '—';
  return new Date(d).toLocaleString();
}

export default function BackupHistoryPage() {
  const [items, setItems] = useState<BackupHistoryItem[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [limit, setLimit] = useState(20);
  const [typeFilter, setTypeFilter] = useState<BackupType | ''>('');
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchHistory = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await backupService.getHistory({
        page,
        limit,
        type: typeFilter || undefined,
      });
      setItems(res.items);
      setTotal(res.total);
    } catch (e: any) {
      setError(e?.message ?? 'Failed to fetch history');
    } finally {
      setLoading(false);
    }
  }, [page, limit, typeFilter]);

  useEffect(() => {
    fetchHistory();
  }, [fetchHistory]);

  const handleVerify = async (id: string) => {
    try {
      await backupService.verifyBackup(id);
      await fetchHistory();
    } catch (e: any) {
      setError(e?.message ?? 'Verification failed');
    }
  };

  const handleDelete = async (id: string) => {
    if (!window.confirm('Delete this backup? This action is irreversible.')) return;
    try {
      await backupService.deleteBackup(id);
      await fetchHistory();
    } catch (e: any) {
      setError(e?.message ?? 'Delete failed');
    }
  };

  const totalPages = Math.max(1, Math.ceil(total / limit));

  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">Backup History</h1>
          <p className="mt-1 text-sm text-white/50">All backup runs, with verification and retention status</p>
        </div>
        <div className="flex items-center gap-3">
          <select
            value={typeFilter}
            onChange={(e) => { setTypeFilter(e.target.value as BackupType | ''); setPage(1); }}
            className="rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-xs text-white/70"
          >
            <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>
          <button
            onClick={fetchHistory}
            className="rounded-lg bg-white/10 px-3 py-2 text-xs text-white/70 hover:bg-white/20 transition-colors"
          >
            Refresh
          </button>
        </div>
      </div>

      {error && (
        <div className="rounded-xl border border-red-500/20 bg-red-500/10 p-4 text-sm text-red-300">{error}</div>
      )}

      <div className="overflow-x-auto rounded-xl border border-white/5">
        <table className="w-full text-left text-sm">
          <thead className="border-b border-white/5 bg-white/[0.02]">
            <tr className="text-[10px] uppercase tracking-wider text-slate-500">
              <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">Size</th>
              <th className="px-4 py-3">Encrypted</th>
              <th className="px-4 py-3">Checksum</th>
              <th className="px-4 py-3">Created</th>
              <th className="px-4 py-3">Actions</th>
            </tr>
          </thead>
          <tbody>
            {loading ? (
              <tr><td colSpan={8} className="px-4 py-8 text-center text-slate-500">Loading…</td></tr>
            ) : items.length === 0 ? (
              <tr><td colSpan={8} className="px-4 py-8 text-center text-slate-500">No backups found</td></tr>
            ) : (
              items.map((item) => (
                <tr key={item.id} className="border-b border-white/5 hover:bg-white/[0.02]">
                  <td className="px-4 py-3 font-medium text-white">{item.type}</td>
                  <td className="px-4 py-3 text-white/60">{item.scope}</td>
                  <td className="px-4 py-3">
                    <span className={`rounded-lg border px-2 py-0.5 text-[10px] font-mono uppercase ${STATUS_STYLES[item.status] ?? 'bg-slate-500/15 text-slate-400 border-slate-500/20'}`}>
                      {item.status}
                    </span>
                  </td>
                  <td className="px-4 py-3 font-mono text-white/60">{formatBytes(item.fileSizeBytes)}</td>
                  <td className="px-4 py-3 text-white/60">{item.isEncrypted ? 'Yes' : 'No'}</td>
                  <td className="px-4 py-3 font-mono text-[10px] text-white/40 truncate max-w-[120px]">{item.checksum ?? '—'}</td>
                  <td className="px-4 py-3 text-white/60">{formatDate(item.createdAt)}</td>
                  <td className="px-4 py-3">
                    <div className="flex gap-2">
                      <button
                        onClick={() => handleVerify(item.id)}
                        disabled={item.status === 'RUNNING' || item.status === 'VERIFYING'}
                        className="rounded-lg bg-white/5 px-2 py-1 text-[10px] text-white/70 hover:bg-white/10 disabled:opacity-40"
                      >
                        Verify
                      </button>
                      <button
                        onClick={() => handleDelete(item.id)}
                        disabled={item.status === 'RUNNING'}
                        className="rounded-lg bg-red-500/10 px-2 py-1 text-[10px] text-red-300 hover:bg-red-500/20 disabled:opacity-40"
                      >
                        Delete
                      </button>
                    </div>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>

      {/* Pagination */}
      <div className="flex items-center justify-between text-xs text-white/50">
        <span>Showing {items.length} of {total}</span>
        <div className="flex gap-2">
          <button
            onClick={() => setPage((p) => Math.max(1, p - 1))}
            disabled={page <= 1}
            className="rounded-lg bg-white/5 px-3 py-1.5 text-white/70 hover:bg-white/10 disabled:opacity-40"
          >
            Prev
          </button>
          <span className="px-2 py-1.5">Page {page} / {totalPages}</span>
          <button
            onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
            disabled={page >= totalPages}
            className="rounded-lg bg-white/5 px-3 py-1.5 text-white/70 hover:bg-white/10 disabled:opacity-40"
          >
            Next
          </button>
        </div>
      </div>
    </div>
  );
}
