import React from 'react';
import { Link } from 'react-router-dom';
import { Activity, Database, Gauge, HardDrive, Play, RefreshCw, Thermometer } from 'lucide-react';
import OfflineBanner from '@/components/scanforge/OfflineBanner';
import Panel from '@/components/scanforge/Panel';
import { useScanner } from '@/context/ScannerContext';
import { scanPath } from '@/lib/appConfig';

const readable = (value, fallback = 'Unavailable') => value === null || value === undefined || value === '' ? fallback : String(value);

export default function Dashboard() {
  const { status, scanState, test, reconnect, demo } = useScanner();
  const health = scanState.health || {};
  const device = scanState.device || {};
  const metrics = [
    ['Kinect', scanState.kinectState.replaceAll('_', ' '), Gauge],
    ['RGB stream', readable(health.rgb_stream ?? health.rgbStream, 'Not reported'), Activity],
    ['Depth stream', readable(health.depth_stream ?? health.depthStream, 'Not reported'), Activity],
    ['Temperature', readable(device.temperature ?? health.temperature, 'Not reported'), Thermometer],
    ['Calibration', readable(scanState.calibrationProfileName, 'No valid profile'), Gauge],
    ['Disk space', readable(health.available_disk ?? health.availableDisk, 'Awaiting agent'), HardDrive],
    ['Last scan', scanState.lastSuccessfulScan ? new Date(scanState.lastSuccessfulScan).toLocaleString() : 'No completed scans', Database],
    ['Active scan', scanState.activeProjectName || 'None', Activity]
  ];

  return (
    <div className="mx-auto max-w-7xl space-y-5">
      <div>
        <p className="text-xs uppercase tracking-[.28em] text-purple-300">Scanner control centre</p>
        <h2 className="mt-2 text-3xl font-semibold tracking-tight">Scanner Dashboard</h2>
        <p className="mt-2 max-w-2xl text-sm text-zinc-400">Local Kinect capture, mesh preparation and 3D-print validation through the SHiRE ScanForge Agent.</p>
      </div>
      {status === 'offline' && !demo && <OfflineBanner />}
      {scanState.error && <div className="rounded-xl border border-red-500/30 bg-red-500/10 p-3 text-sm text-red-200">{scanState.error}</div>}
      <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
        {metrics.map(([name, value, Icon]) => (
          <div key={name} className="rounded-2xl border border-white/10 bg-[#111114] p-4">
            <div className="flex items-center justify-between text-zinc-500"><span className="text-xs uppercase tracking-wider">{name}</span><Icon size={16}/></div>
            <p className="mt-3 capitalize font-medium text-zinc-200">{value}</p>
          </div>
        ))}
      </div>
      <div className="grid gap-5 xl:grid-cols-[1.4fr_.8fr]">
        <Panel title="Start a scan" eyebrow="Quick actions">
          <p className="mb-5 text-sm text-zinc-400">Ready appears only after the ScanForge Agent confirms a working bridge and Kinect depth stream.</p>
          <div className="flex flex-wrap gap-3">
            <Link to={scanPath('new-scan')} className="flex items-center gap-2 rounded-xl bg-[#7dff72] px-4 py-3 text-sm font-bold text-black"><Play size={17}/>Quick Start Scan</Link>
            <button onClick={() => test().catch(() => {})} className="flex items-center gap-2 rounded-xl border border-white/15 px-4 py-3 text-sm"><Activity size={17}/>Run Scanner Test</button>
            <button onClick={() => reconnect().catch(() => {})} className="flex items-center gap-2 rounded-xl border border-white/15 px-4 py-3 text-sm"><RefreshCw size={17}/>Restart ScanForge Agent</button>
          </div>
        </Panel>
        <Panel title="Current operation" eyebrow="Agent status">
          <dl className="space-y-3 text-sm">
            <div className="flex justify-between gap-4"><dt className="text-zinc-500">Agent</dt><dd className="capitalize">{scanState.agentState}</dd></div>
            <div className="flex justify-between gap-4"><dt className="text-zinc-500">Bridge</dt><dd className="capitalize">{scanState.bridgeState}</dd></div>
            <div className="flex justify-between gap-4"><dt className="text-zinc-500">Operation</dt><dd className="capitalize">{scanState.operation}</dd></div>
            <div className="flex justify-between gap-4"><dt className="text-zinc-500">Progress</dt><dd>{scanState.progress || 0}%</dd></div>
          </dl>
        </Panel>
      </div>
    </div>
  );
}
