import { useEffect, useState } from 'react';
import { RefreshCw, Smartphone, Download, ShieldCheck } from 'lucide-react';
import { formatDistanceToNow } from 'date-fns';
import { useDeviceStore } from '../devices/useDeviceStore';
import { MetricCard } from '../devices/MetricCard';
import { MetricChartModal } from '../devices/MetricChartModal';
import {
  PROVIDER_CONFIG,
  type Provider, type APIDeviceConnection, type MetricId,
} from '../devices/types';

// Order matters — this is also the display order on the cards grid.
const DISPLAY_METRICS: MetricId[] = [
  'steps',
  'sleep_duration',
  'heart_rate_resting',
  'blood_oxygen',
  'calories_total',
  'calories_intake',
  'basal_metabolic_rate',
  'weight',
  'body_fat',
  'blood_glucose',
  'blood_pressure_sys',
  'blood_pressure_dia',
];

export function DevicesPage() {
  const {
    connections, summary, isLoading,
    loadConnections, loadSummary,
    disconnectProvider, toggleSharing,
  } = useDeviceStore();

  const [chartMetric, setChartMetric] = useState<string | null>(null);
  const [confirmDisconnect, setConfirmDisconnect] = useState<string | null>(null);

  useEffect(() => {
    loadConnections();
    loadSummary();
  }, [loadConnections, loadSummary]);

  const activeConnections = connections.filter(c => c.status === 'active');
  const metricsWithData = DISPLAY_METRICS.filter(m => summary[m]);

  return (
    <div className="pb-20">
      {/* Header */}
      <div className="mb-8">
        <h1 className="text-2xl font-semibold text-gray-900">Devices &amp; Health Apps</h1>
        <p className="text-gray-500 text-sm mt-1">
          Sync data from your Galaxy Watch and Samsung Health using the Hipograf Companion app
        </p>
      </div>

      {/* Connected Devices */}
      {activeConnections.length > 0 && (
        <section className="mb-8">
          <h3 className="text-sm font-medium text-gray-500 uppercase tracking-wide mb-4 flex items-center gap-2">
            Connected
            <span className="text-xs bg-emerald-100 text-emerald-700 px-2 py-0.5 rounded-full font-semibold">
              {activeConnections.length}
            </span>
          </h3>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {activeConnections.map(conn => (
              <ConnectionCard
                key={conn._id}
                conn={conn}
                confirmingDisconnect={confirmDisconnect === conn._id}
                onToggleSharing={(shared) => toggleSharing(conn._id, shared)}
                onDisconnect={() => {
                  if (confirmDisconnect === conn._id) {
                    disconnectProvider(conn._id);
                    setConfirmDisconnect(null);
                  } else {
                    setConfirmDisconnect(conn._id);
                  }
                }}
                onCancelDisconnect={() => setConfirmDisconnect(null)}
              />
            ))}
          </div>
        </section>
      )}

      {/* Latest Readings */}
      {metricsWithData.length > 0 && (
        <section className="mb-8">
          <h3 className="text-sm font-medium text-gray-500 uppercase tracking-wide mb-4">
            Latest Readings
          </h3>
          <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-3">
            {metricsWithData.map(metricId => {
              const s = summary[metricId];
              return (
                <MetricCard
                  key={metricId}
                  metricId={metricId}
                  value={s?.value ?? null}
                  date={s?.date ?? null}
                  provider={(s?.provider as Provider) ?? null}
                  onClick={() => setChartMetric(metricId)}
                />
              );
            })}
          </div>
        </section>
      )}

      {/* Companion app onboarding (only if not connected) */}
      {activeConnections.length === 0 && !isLoading && (
        <CompanionAppOnboarding />
      )}

      {/* Chart Modal */}
      <MetricChartModal
        metricId={chartMetric || ''}
        isOpen={!!chartMetric}
        onClose={() => setChartMetric(null)}
      />
    </div>
  );
}


// ─── Companion App Onboarding ───────────────────────────────────────

function CompanionAppOnboarding() {
  const samsung = PROVIDER_CONFIG.samsung_health;
  return (
    <section>
      <div className="rounded-2xl border border-gray-200 bg-white overflow-hidden">
        <div
          className="p-6 sm:p-8 text-white"
          style={{ background: `linear-gradient(135deg, ${samsung.brandColor} 0%, #2563eb 100%)` }}
        >
          <div className="flex items-start gap-4">
            <div className="w-14 h-14 rounded-2xl bg-white/15 backdrop-blur-sm flex items-center justify-center shrink-0">
              <Smartphone className="w-7 h-7" />
            </div>
            <div>
              <h3 className="text-xl font-semibold">Connect Samsung Health</h3>
              <p className="text-sm text-white/80 mt-1 max-w-lg">
                Hipograf reads your Galaxy Watch and Samsung Health data through Android Health Connect.
                Install the companion app on your Android phone and your data will sync automatically.
              </p>
            </div>
          </div>
        </div>

        <div className="p-6 sm:p-8 grid grid-cols-1 md:grid-cols-3 gap-6">
          <Step
            num={1}
            icon={<Download className="w-5 h-5" />}
            title="Install the companion app"
            body="Open the Hipograf Companion app on your Android phone."
          />
          <Step
            num={2}
            icon={<ShieldCheck className="w-5 h-5" />}
            title="Grant permissions"
            body="Sign in with your Hipograf account and allow Health Connect read access for the data you want to share."
          />
          <Step
            num={3}
            icon={<RefreshCw className="w-5 h-5" />}
            title="Tap Sync"
            body="Tap Sync Now in the companion app. Your data will appear here within a few seconds."
          />
        </div>

        <div className="px-6 sm:px-8 pb-6 pt-2 text-xs text-gray-500 border-t border-gray-100 pt-4">
          <strong className="text-gray-700">Tip:</strong>{' '}
          If your data isn&apos;t showing up, open Samsung Health on your phone, go to{' '}
          <span className="font-medium">Settings → Health Connect</span>, and make sure the categories
          you want (steps, heart rate, sleep, etc.) are enabled.
        </div>
      </div>
    </section>
  );
}

function Step({
  num, icon, title, body,
}: { num: number; icon: React.ReactNode; title: string; body: string }) {
  return (
    <div>
      <div className="flex items-center gap-3 mb-2">
        <div className="w-9 h-9 rounded-xl bg-blue-50 text-blue-600 flex items-center justify-center">
          {icon}
        </div>
        <span className="text-xs font-semibold text-gray-400">STEP {num}</span>
      </div>
      <h4 className="font-semibold text-gray-900 text-sm mb-1">{title}</h4>
      <p className="text-xs text-gray-500 leading-relaxed">{body}</p>
    </div>
  );
}


// ─── Connection Card ────────────────────────────────────────────────

function ConnectionCard({
  conn, confirmingDisconnect,
  onToggleSharing, onDisconnect, onCancelDisconnect,
}: {
  conn: APIDeviceConnection;
  confirmingDisconnect: boolean;
  onToggleSharing: (shared: boolean) => void;
  onDisconnect: () => void;
  onCancelDisconnect: () => void;
}) {
  const prov = PROVIDER_CONFIG[conn.provider];
  const lastSyncLabel = conn.lastSyncAt
    ? formatDistanceToNow(new Date(conn.lastSyncAt), { addSuffix: true })
    : 'Never';

  const isRecent = conn.lastSyncAt &&
    Date.now() - new Date(conn.lastSyncAt).getTime() < 2 * 60 * 60 * 1000;

  // Pull device info from metadata if the companion app sent it
  const deviceModel = (conn.metadata?.model as string | undefined)
    ?? (conn.metadata?.manufacturer as string | undefined);
  const deviceOs = conn.metadata?.osVersion as string | undefined;

  return (
    <div className="p-5 rounded-xl border border-gray-200 bg-white">
      <div className="flex items-start justify-between gap-3">
        <div className="flex items-center gap-3 min-w-0">
          <div
            className="w-11 h-11 rounded-xl flex items-center justify-center text-white font-bold shrink-0"
            style={{ backgroundColor: prov.brandColor }}
          >
            {prov.name[0]}
          </div>
          <div className="min-w-0">
            <h4 className="font-semibold text-gray-900 text-sm truncate">{prov.name}</h4>
            <div className="flex items-center gap-1.5 mt-0.5">
              <span className={`w-1.5 h-1.5 rounded-full ${isRecent ? 'bg-emerald-400' : 'bg-amber-400'}`} />
              <span className="text-[11px] text-gray-400 truncate">
                Last sync {lastSyncLabel}
              </span>
            </div>
            {(deviceModel || deviceOs) && (
              <p className="text-[11px] text-gray-400 mt-0.5 truncate">
                {[deviceModel, deviceOs].filter(Boolean).join(' · ')}
              </p>
            )}
          </div>
        </div>
      </div>

      <div className="mt-4 pt-3 border-t border-gray-100 flex items-center justify-between">
        <label className="flex items-center gap-2 cursor-pointer">
          <div className="relative">
            <input
              type="checkbox"
              checked={conn.sharedWithPractitioners}
              onChange={(e) => onToggleSharing(e.target.checked)}
              className="sr-only peer"
            />
            <div className="w-8 h-[18px] bg-gray-200 peer-checked:bg-emerald-400 rounded-full transition-colors" />
            <div className="absolute top-0.5 left-0.5 w-3.5 h-3.5 bg-white rounded-full shadow-sm transition-transform peer-checked:translate-x-[14px]" />
          </div>
          <span className="text-xs text-gray-500">Share with doctors</span>
        </label>

        {confirmingDisconnect ? (
          <div className="flex items-center gap-2">
            <span className="text-xs text-red-500">Sure?</span>
            <button onClick={onDisconnect} className="text-xs text-red-600 font-medium hover:underline">
              Yes
            </button>
            <button onClick={onCancelDisconnect} className="text-xs text-gray-400 hover:underline">
              No
            </button>
          </div>
        ) : (
          <button onClick={onDisconnect} className="text-xs text-red-400 hover:text-red-600 transition-colors">
            Disconnect
          </button>
        )}
      </div>
    </div>
  );
}
