'use client';
import { useEffect, useState, useCallback } from 'react';
import Link from 'next/link';
import { backupService } from '@/services/backup.service';
import type { BackupStatusOverview } 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',
  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]}`;
}

export default function BackupDashboardPage() {
  const [status, setStatus] = useState<BackupStatusOverview | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [creating, setCreating] = useState(false);
  const [message, setMessage] = useState<string | null>(null);

  const fetchStatus = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await backupService.getStatus();
      setStatus(res);
    } catch (e: any) {
      setError(e?.message ?? 'Failed to fetch backup status');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchStatus();
  }, [fetchStatus]);

  const handleManualBackup = async () => {
    setCreating(true);
    setMessage(null);
    setError(null);
    try {
      const result = await backupService.createBackup({ type: 'MANUAL', scope: 'FULL' });
      setMessage(`Backup started: ${result.backupId}`);
      await fetchStatus();
    } catch (e: any) {
      setError(e?.message ?? 'Failed to start backup');
    } finally {
      setCreating(false);
    }
  };

  const byStatusCount = (s: string) =>
    status?.byStatus.find((b) => b.status === s)?._count ?? 0;

  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 &amp; Restore</h1>
          <p className="mt-1 text-sm text-white/50">Enterprise backup dashboard — database + files</p>
        </div>
        <div className="flex items-center gap-3">
          <Link
            href="/admin/backup/history"
            className="rounded-lg bg-white/5 px-3 py-2 text-xs text-white/70 hover:bg-white/10 transition-colors"
          >
            History
          </Link>
          <Link
            href="/admin/backup/restore"
            className="rounded-lg bg-white/5 px-3 py-2 text-xs text-white/70 hover:bg-white/10 transition-colors"
          >
            Restore
          </Link>
          <button
            onClick={handleManualBackup}
            disabled={creating}
            className="rounded-lg bg-blue-600 px-4 py-2 text-xs font-medium text-white hover:bg-blue-500 disabled:opacity-50 transition-colors"
          >
            {creating ? 'Starting…' : 'Run Manual Backup'}
          </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>
      )}
      {message && (
        <div className="rounded-xl border border-emerald-500/20 bg-emerald-500/10 p-4 text-sm text-emerald-300">{message}</div>
      )}

      {loading && !status ? (
        <div className="animate-pulse space-y-4">
          {[1, 2, 3].map((i) => (
            <div key={i} className="h-24 rounded-xl bg-white/[0.03]" />
          ))}
        </div>
      ) : status ? (
        <div className="space-y-6">
          {/* Summary cards */}
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
            <div className="rounded-xl border border-white/5 bg-white/[0.02] p-4">
              <p className="text-[10px] uppercase tracking-wider text-slate-500">Total Backups</p>
              <p className="mt-1 font-mono text-2xl text-white">{status.total}</p>
            </div>
            <div className="rounded-xl border border-white/5 bg-white/[0.02] p-4">
              <p className="text-[10px] uppercase tracking-wider text-slate-500">Total Size</p>
              <p className="mt-1 font-mono text-2xl text-white">{formatBytes(status.totalSizeBytes)}</p>
            </div>
            <div className="rounded-xl border border-white/5 bg-white/[0.02] p-4">
              <p className="text-[10px] uppercase tracking-wider text-slate-500">Completed</p>
              <p className="mt-1 font-mono text-2xl text-emerald-400">{byStatusCount('COMPLETED')}</p>
            </div>
            <div className="rounded-xl border border-white/5 bg-white/[0.02] p-4">
              <p className="text-[10px] uppercase tracking-wider text-slate-500">Failed</p>
              <p className="mt-1 font-mono text-2xl text-red-400">{byStatusCount('FAILED')}</p>
            </div>
          </div>

          {/* Status by type */}
          <div>
            <h3 className="mb-3 text-sm font-medium text-white">Backups by Type</h3>
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
              {['DAILY', 'WEEKLY', 'MONTHLY', 'MANUAL'].map((t) => {
const count = status.byType.find((b) => b.type === t)?._count ?? 0;
                return (
                  <div key={t} className="rounded-xl border border-white/5 bg-white/[0.02] p-4">
                    <p className="text-xs font-medium text-white">{t}</p>
                    <p className="mt-1 font-mono text-xl text-white">{count}</p>
                  </div>
                );
              })}
            </div>
          </div>

          {/* Retention */}
          <div className="rounded-xl border border-white/5 bg-white/[0.02] p-4">
            <h3 className="mb-3 text-sm font-medium text-white">Retention Policy</h3>
            <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
              <div className="rounded-lg bg-white/[0.02] p-3">
                <p className="text-[10px] uppercase tracking-wider text-slate-500">Daily</p>
                <p className="mt-1 font-mono text-sm text-white">{status.retention.dailyDays} days</p>
              </div>
              <div className="rounded-lg bg-white/[0.02] p-3">
                <p className="text-[10px] uppercase tracking-wider text-slate-500">Weekly</p>
                <p className="mt-1 font-mono text-sm text-white">{status.retention.weeklyWeeks} weeks</p>
              </div>
              <div className="rounded-lg bg-white/[0.02] p-3">
                <p className="text-[10px] uppercase tracking-wider text-slate-500">Monthly</p>
                <p className="mt-1 font-mono text-sm text-white">{status.retention.monthlyMonths} months</p>
              </div>
            </div>
          </div>
        </div>
      ) : null}
    </div>
  );
}
