import { Box, Circle, Container, Plus, Server, Timer } from 'lucide-react';

export function Dashboard({ health, jobs, loading, onCreateSchedule, onManage, schedules, vms }) {
  const scheduleByVm = new Map((schedules || []).map((schedule) => [`${schedule.nodeId}:${schedule.vmName}`, schedule]));

  return (
    <section className="space-y-5">
      <div className="grid gap-5 xl:grid-cols-3">
        {vms.map((vm) => {
          const activeJob = vm.activeJob || jobs.find((job) => job.nodeId === vm.nodeId && job.vmName === vm.name && ['queued', 'running'].includes(job.status));
          const lastJob = jobs.find((job) => job.nodeId === vm.nodeId && job.vmName === vm.name && job.status === 'success');
          const schedule = scheduleByVm.get(`${vm.nodeId}:${vm.name}`);
          return (
            <button
              className="group relative min-h-[178px] overflow-hidden border border-zinc-700 bg-zinc-950/80 p-7 text-left outline-none transition hover:border-zinc-500 focus:border-red-400"
              key={vm.id || `${vm.nodeId}:${vm.name}`}
              onClick={() => onManage(vm.id || vm.name)}
              type="button"
            >
              <CornerFrame />
              <div className="flex items-start justify-between gap-5">
                <div className="min-w-0">
                  <div className="flex items-center gap-3">
                    {vm.type === 'container' ? <Container className="h-5 w-5 text-zinc-400" /> : <Box className="h-5 w-5 text-zinc-400" />}
                    <h2 className="truncate text-xl font-bold tracking-wide text-zinc-100">{vm.name}</h2>
                  </div>
                  <div className="mt-3 flex items-center gap-2 text-sm text-zinc-500">
                    <Server className="h-4 w-4" />
                    <span className="truncate">{vm.nodeName || 'Unknown node'}</span>
                    <span className="text-red-400">→</span>
                    <span>{vm.type === 'container' ? 'Container' : 'VM'}</span>
                  </div>
                </div>
                <Circle className={`mt-1 h-4 w-4 shrink-0 fill-current ${vm.status === 'Running' ? 'text-emerald-400' : 'text-zinc-600'}`} />
              </div>

              <dl className="mt-10 space-y-3 text-sm">
                <Metric label="Schedule" value={scheduleLabel(schedule)} />
                <Metric label="Last backup" value={lastJob ? relativeTime(lastJob.finishedAt || lastJob.createdAt) : vm.lastJobStatus || 'None'} />
                <Metric label="Next backup" value={schedule?.enabled && schedule.nextRunAt ? formatDateTime(schedule.nextRunAt) : '-'} />
              </dl>

              {activeJob ? (
                <div className="mt-5">
                  <div className="flex items-center justify-between gap-3 text-xs text-zinc-400">
                    <span className="truncate">{activeJob.currentStep || activeJob.status}</span>
                    <span className="font-mono">{Math.round(activeJob.progress?.percent || 0)}%</span>
                  </div>
                  <div className="mt-2 h-1.5 overflow-hidden rounded-sm bg-zinc-800">
                    <div className="h-full bg-cyan-400" style={{ width: `${Math.round(activeJob.progress?.percent || 0)}%` }} />
                  </div>
                </div>
              ) : null}
            </button>
          );
        })}

        <button
          className="flex min-h-[178px] flex-col items-center justify-center gap-5 border border-dashed border-zinc-700 bg-zinc-950/50 text-zinc-100 transition hover:border-zinc-500"
          onClick={onCreateSchedule}
          type="button"
        >
          <span className="flex h-16 w-16 items-center justify-center rounded-full bg-zinc-900 text-zinc-200">
            <Plus className="h-7 w-7" />
          </span>
          <span className="font-semibold tracking-wide">Create a backup schedule</span>
        </button>
      </div>

      {!vms.length ? (
        <div className="border border-zinc-800 bg-zinc-950/80 px-5 py-10 text-center text-sm text-zinc-500">
          {loading ? 'Loading instances...' : 'No VMs or containers loaded.'}
        </div>
      ) : null}

      <div className="flex items-center gap-2 text-xs text-zinc-500">
        <Timer className="h-4 w-4" />
        <span>{healthSummary(health)}</span>
      </div>
    </section>
  );
}

function Metric({ label, value }) {
  return (
    <div className="grid grid-cols-[auto_1fr_auto] items-center gap-3 text-zinc-400">
      <dt className="font-medium">{label}</dt>
      <dd className="border-b border-dashed border-zinc-800" />
      <dd className="max-w-[13rem] truncate text-right font-semibold text-zinc-200">{value}</dd>
    </div>
  );
}

function CornerFrame() {
  return (
    <>
      <span className="pointer-events-none absolute left-0 top-0 h-5 w-5 border-l-2 border-t-2 border-zinc-600 transition group-hover:border-zinc-400" />
      <span className="pointer-events-none absolute right-0 top-0 h-5 w-5 border-r-2 border-t-2 border-zinc-600 transition group-hover:border-zinc-400" />
      <span className="pointer-events-none absolute bottom-0 left-0 h-5 w-5 border-b-2 border-l-2 border-zinc-600 transition group-hover:border-zinc-400" />
      <span className="pointer-events-none absolute bottom-0 right-0 h-5 w-5 border-b-2 border-r-2 border-zinc-600 transition group-hover:border-zinc-400" />
    </>
  );
}

function scheduleLabel(schedule) {
  if (!schedule?.enabled) return '-';
  if (schedule.timeOfDay) return schedule.timeOfDay;
  return schedule.cron || 'enabled';
}

function formatDateTime(value) {
  if (!value) return '-';
  return new Intl.DateTimeFormat(undefined, { dateStyle: 'short', timeStyle: 'short' }).format(new Date(value));
}

function relativeTime(value) {
  if (!value) return 'None';
  const diffMs = Date.now() - new Date(value).getTime();
  const diffMinutes = Math.max(0, Math.round(diffMs / 60000));
  if (diffMinutes < 1) return 'just now';
  if (diffMinutes < 60) return `${diffMinutes} min ago`;
  const diffHours = Math.round(diffMinutes / 60);
  if (diffHours < 48) return `${diffHours} hours ago`;
  return `${Math.round(diffHours / 24)} days ago`;
}

function healthSummary(health) {
  if (!health) return 'Health loading';
  if (health.ok) return 'All checks ok';
  return Object.entries(health.checks || {})
    .filter(([, value]) => value !== 'ok')
    .map(([key]) => key)
    .join(', ') || 'Health degraded';
}
