'use client';
import { useEffect, useState, useCallback } from 'react';
import { backupService } from '@/services/backup.service';
import type { BackupHistoryItem, BackupVerification } from '@/types/backup.types';

function formatDate(d?: string): string {
  if (!d) return '—';
  return new Date(d).toLocaleString();
}

export default function BackupVerificationPage() {
  const [backups, setBackups] = useState<BackupHistoryItem[]>([]);
  const [expanded, setExpanded] = useState<Record<string, boolean>>({});
  const [verifications, setVerifications] = useState<Record<string, BackupVerification[]>>({});
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchBackups = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await backupService.getHistory({ limit: 50 });
      setBackups(res.items);
    } catch (e: any) {
      setError(e?.message ?? 'Failed to load backups');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchBackups();
  }, [fetchBackups]);

  const toggleExpand = async (id: string) => {
    const next = { ...expanded, [id]: !expanded[id] };
    setExpanded(next);
    if (next[id] && !verifications[id]) {
      try {
        const detail = await backupService.getBackup(id);
        setVerifications((prev) => ({ ...prev, [id]: detail.verifications ?? [] }));
      } catch (e: any) {
        setError(e?.message ?? 'Failed to load verifications');
      }
    }
  };

  const handleVerify = async (id: string) => {
    setError(null);
    try {
      const result = await backupService.verifyBackup(id);
      setVerifications((prev) => ({ ...prev, [id]: [result, ...(prev[id] ?? [])] }));
    } catch (e: any) {
      setError(e?.message ?? 'Verification failed');
    }
  };

  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 Verification</h1>
          <p className="mt-1 text-sm text-white/50">Verify checksum integrity and decryptability of backups</p>
        </div>
        <button
          onClick={fetchBackups}
          className="rounded-lg bg-white/10 px-3 py-2 text-xs text-white/70 hover:bg-white/20 transition-colors"
        >
          Refresh
        </button>
      </div>

      {error && (
        <div className="rounded-xl border border-red-500/20 bg-red-500/10 p-4 text-sm text-red-300">{error}</div>
      )}

      {loading ? (
        <div className="animate-pulse space-y-3">
          {[1, 2, 3].map((i) => (
            <div key={i} className="h-20 rounded-xl bg-white/[0.03]" />
          ))}
        </div>
      ) : backups.length === 0 ? (
        <div className="rounded-xl border border-white/5 bg-white/[0.02] p-8 text-center text-sm text-slate-500">
          No backups to verify
        </div>
      ) : (
        <div className="space-y-3">
          {backups.map((b) => (
            <div key={b.id} className="rounded-xl border border-white/5 bg-white/[0.02] p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-white">
                    {b.type} · {b.scope}
                  </p>
                  <p className="mt-0.5 text-[10px] font-mono text-slate-500">{formatDate(b.createdAt)}</p>
                </div>
                <div className="flex items-center gap-2">
                  <span className={`rounded-lg border px-2 py-0.5 text-[10px] font-mono uppercase ${
                    b.status === 'COMPLETED'
                      ? 'bg-emerald-500/15 text-emerald-400 border-emerald-500/20'
                      : 'bg-slate-500/15 text-slate-400 border-slate-500/20'
                  }`}>
                    {b.status}
                  </span>
                  <button
                    onClick={() => handleVerify(b.id)}
                    disabled={b.status === 'RUNNING' || b.status === 'VERIFYING'}
                    className="rounded-lg bg-blue-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-blue-500 disabled:opacity-40"
                  >
                    Verify Now
                  </button>
                  <button
                    onClick={() => toggleExpand(b.id)}
                    className="rounded-lg bg-white/5 px-3 py-1.5 text-xs text-white/70 hover:bg-white/10"
                  >
                    {expanded[b.id] ? 'Hide' : 'History'}
                  </button>
                </div>
              </div>

              {b.checksum && (
                <p className="mt-2 font-mono text-[10px] text-slate-500 break-all">
                  SHA-256: {b.checksum}
                </p>
              )}

              {expanded[b.id] && (
                <div className="mt-3 space-y-2">
                  {(verifications[b.id] ?? []).length === 0 ? (
                    <p className="text-xs text-slate-500">No verification records yet.</p>
                  ) : (
                    verifications[b.id]!.map((v) => (
                      <div key={v.id} className="rounded-lg bg-white/[0.02] p-3 text-xs">
                        <div className="flex items-center justify-between">
                          <span className={`font-medium ${
                            v.status === 'PASSED' ? 'text-emerald-400' : 'text-red-400'
                          }`}>
                            {v.status}
                          </span>
                          <span className="text-slate-500">{formatDate(v.verifiedAt)}</span>
                        </div>
                        <div className="mt-1 grid grid-cols-2 gap-2 text-slate-400">
                          <span>Checksum match: {v.checksumMatched ? '✓' : '✗'}</span>
                          <span>File exists: {v.fileExists ? '✓' : '✗'}</span>
                          <span>Can decrypt: {v.canDecrypt ? '✓' : '✗'}</span>
                          <span>Size: {v.fileSizeBytes ?? '—'}</span>
                        </div>
                        {v.errorMessage && (
                          <p className="mt-1 text-red-400">{v.errorMessage}</p>
                        )}
                      </div>
                    ))
                  )}
                </div>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
