import { create } from 'zustand';
import { apiFetch } from '../services/api';
import type {
  APIDeviceConnection,
  APIDeviceReading,
  DeviceSummaryResponse,
  MetricSummary,
  Provider,
} from './types';

interface DeviceState {
  connections: APIDeviceConnection[];
  summary: Record<string, MetricSummary>;
  connectedProviders: Provider[];
  lastSync: string | null;
  metricHistory: APIDeviceReading[];
  isLoading: boolean;
  error: string | null;

  loadConnections: () => Promise<void>;
  loadSummary: () => Promise<void>;
  loadMetricHistory: (metric: string, startDate: string, endDate: string) => Promise<void>;
  disconnectProvider: (connectionId: string) => Promise<void>;
  toggleSharing: (connectionId: string, shared: boolean) => Promise<void>;
}

export const useDeviceStore = create<DeviceState>((set, get) => ({
  connections: [],
  summary: {},
  connectedProviders: [],
  lastSync: null,
  metricHistory: [],
  isLoading: false,
  error: null,

  loadConnections: async () => {
    try {
      set({ isLoading: true, error: null });
      const data = await apiFetch<APIDeviceConnection[]>('/devices/connections');
      set({ connections: data, isLoading: false });
    } catch (e) {
      console.error('Failed to load connections', e);
      set({ isLoading: false, error: (e as Error).message });
    }
  },

  loadSummary: async () => {
    try {
      set({ isLoading: true, error: null });
      const data = await apiFetch<DeviceSummaryResponse>('/devices/summary');
      set({
        summary: data.summary,
        connectedProviders: data.connectedProviders,
        lastSync: data.lastSync,
        isLoading: false,
      });
    } catch (e) {
      console.error('Failed to load summary', e);
      set({ isLoading: false, error: (e as Error).message });
    }
  },

  loadMetricHistory: async (metric, startDate, endDate) => {
    try {
      set({ isLoading: true, error: null });
      const params = new URLSearchParams({ metric, start_date: startDate, end_date: endDate });
      const data = await apiFetch<APIDeviceReading[]>(`/devices/data?${params.toString()}`);
      set({ metricHistory: data, isLoading: false });
    } catch (e) {
      console.error('Failed to load metric history', e);
      set({ isLoading: false, error: (e as Error).message });
    }
  },

  disconnectProvider: async (connectionId) => {
    try {
      await apiFetch(`/devices/connections/${connectionId}`, { method: 'DELETE' });
      await get().loadConnections();
      await get().loadSummary();
    } catch (e) {
      console.error('Failed to disconnect', e);
      set({ error: (e as Error).message });
    }
  },

  toggleSharing: async (connectionId, shared) => {
    try {
      await apiFetch(`/devices/connections/${connectionId}/sharing`, {
        method: 'PATCH',
        body: JSON.stringify({ sharedWithPractitioners: shared }),
      });
      await get().loadConnections();
    } catch (e) {
      console.error('Failed to toggle sharing', e);
      set({ error: (e as Error).message });
    }
  },
}));
