import { create } from 'zustand';
import { apiFetch } from '../lib/api';
import { getDeviceInfo } from '../lib/deviceId';

export interface UserDevice {
  id: string;
  deviceId: string;
  platform: string;
  model: string | null;
  name: string | null;
  lastSeenAt: string;
  createdAt: string;
  isCurrent?: boolean;
  boundToPlan: 'free' | 'pro' | 'legend' | 'standard' | 'premium' | null;
  releaseRequestedAt: string | null;
}

type DevicesState = {
  devices: UserDevice[];
  maxDevices: number;
  plan: string;
  loading: boolean;

  ensureRegistered: () => Promise<void>;
  loadDevices: () => Promise<void>;
  removeDevice: (id: string) => Promise<void>;
  requestRelease: (id: string) => Promise<void>;
  cancelRelease: (id: string) => Promise<void>;
  reset: () => void;
};

export const useDevicesStore = create<DevicesState>((set) => ({
  devices: [],
  maxDevices: 1,
  plan: 'free',
  loading: false,

  ensureRegistered: async () => {
    const info = await getDeviceInfo().catch(() => null);
    if (!info) return;

    await apiFetch('/api/devices/register', {
      method: 'POST',
      skipDeviceHeader: true,
      body: {
        deviceId: info.deviceId,
        platform: info.platform,
        name: info.name,
        model: info.model,
        osVersion: info.osVersion,
        appVersion: info.appVersion,
      },
    }).then((res: any) => {
      set({ maxDevices: res.max ?? 1 });
    }).catch(() => {});
  },

  loadDevices: async () => {
    set({ loading: true });
    try {
      await useDevicesStore.getState().ensureRegistered();
      const res = await apiFetch<{ devices: UserDevice[]; max: number; plan: string }>(
        '/api/devices'
      );
      set({ devices: res.devices, maxDevices: res.max, plan: res.plan });
    } finally {
      set({ loading: false });
    }
  },

  removeDevice: async (id: string) => {
    await apiFetch(`/api/devices/${id}`, { method: 'DELETE' });
    set((s) => ({ devices: s.devices.filter((d) => d.id !== id) }));
  },

  requestRelease: async (id: string) => {
    await apiFetch(`/api/devices/${id}/request-release`, { method: 'POST' });
    const now = new Date().toISOString();
    set((s) => ({
      devices: s.devices.map((d) =>
        d.id === id ? { ...d, releaseRequestedAt: now } : d
      ),
    }));
  },

  cancelRelease: async (id: string) => {
    await apiFetch(`/api/devices/${id}/cancel-release`, { method: 'POST' });
    set((s) => ({
      devices: s.devices.map((d) =>
        d.id === id ? { ...d, releaseRequestedAt: null } : d
      ),
    }));
  },

  reset: () => set({ devices: [], maxDevices: 1, plan: 'free', loading: false }),
}));
