import { useEffect } from 'react';
import { Watch } from 'lucide-react';
import { useDeviceStore } from './useDeviceStore';
import { MetricCard } from './MetricCard';
import type { Provider } from './types';

const DASHBOARD_METRICS = [
  'steps', 'sleep_duration', 'heart_rate_resting',
  'blood_oxygen', 'calories_total', 'weight',
];

export function DeviceSummaryWidget({ size }: { size: 'normal' | 'compact' }) {
  const { summary, connectedProviders, loadSummary, isLoading } = useDeviceStore();

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

  if (isLoading && !Object.keys(summary).length) {
    return <p className="text-xs text-gray-400 p-2">Loading device data...</p>;
  }

  if (connectedProviders.length === 0) {
    return (
      <div className="flex flex-col items-center justify-center py-6 text-center">
        <Watch className="w-8 h-8 text-gray-300 mb-2" />
        <p className="text-sm text-gray-500 mb-1">No devices connected</p>
        <a href="/devices" className="text-xs text-blue-500 hover:underline">
          Connect a device
        </a>
      </div>
    );
  }

  const metricsToShow = DASHBOARD_METRICS.filter(m => summary[m]);
  const maxItems = size === 'compact' ? 4 : 6;

  return (
    <div>
      <div className={`grid ${size === 'compact' ? 'grid-cols-2' : 'grid-cols-2 sm:grid-cols-3'} gap-2`}>
        {metricsToShow.slice(0, maxItems).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}
              compact
            />
          );
        })}
      </div>
      <a
        href="/devices"
        className="block text-center text-xs text-blue-500 hover:underline mt-3"
      >
        View all device data
      </a>
    </div>
  );
}
