import { useCallback, useState } from 'react';
import { Alert } from 'react-native';
import { tcpService } from '../services/TcpService';
import { handleIncomingFrame, deviceSetup, deviceStartContinuous, deviceStartSingle, deviceStop, flushPendingData } from '../services/DeviceService';
import { useConnectionStore } from '../stores/connectionStore';
import { useDeviceStore } from '../stores/deviceStore';
import type { SetupConfig } from '../protocol/types';

export function useDevice() {
  const [busy, setBusy] = useState(false);
  const connStore = useConnectionStore();
  const devStore = useDeviceStore();

  const connect = useCallback(() => {
    const { host, port, setStatus, setError } = useConnectionStore.getState();
    setStatus('connecting');
    tcpService.connect(host, port, {
      onConnect: () => setStatus('connected'),
      onFrame: handleIncomingFrame,
      onError: (err) => setError(err.message),
      onClose: () => {
        if (useConnectionStore.getState().status === 'connected') {
          setStatus('reconnecting');
        }
      },
    });
  }, []);

  const disconnect = useCallback(() => {
    tcpService.disconnect();
    useConnectionStore.getState().setStatus('disconnected');
    useDeviceStore.getState().setDeviceStatus('idle');
  }, []);

  const checkConn = () => {
    if (!tcpService.isConnected()) {
      Alert.alert('未连接', '请先连接设备');
      return false;
    }
    return true;
  };

  const setup = useCallback(async (cfg?: SetupConfig) => {
    if (!checkConn()) return;
    const config = cfg ?? useDeviceStore.getState().config;
    setBusy(true);
    try {
      const ack = await deviceSetup(config);
      if (ack.result !== 0x01) {
        Alert.alert('配置失败', ack.reason || '设备返回失败');
      } else {
        useDeviceStore.getState().setConfigDirty(false);
        Alert.alert('配置成功', '参数已下发到设备');
      }
      return ack;
    } catch (e: any) {
      Alert.alert('配置超时', e.message);
    } finally {
      setBusy(false);
    }
  }, []);

  const startContinuous = useCallback(async () => {
    if (!checkConn()) return;
    setBusy(true);
    try {
      const ack = await deviceStartContinuous();
      if (ack.result !== 0x01) Alert.alert('启动失败', ack.reason);
      return ack;
    } catch (e: any) {
      Alert.alert('启动超时', e.message);
    } finally {
      setBusy(false);
    }
  }, []);

  const startSingle = useCallback(async () => {
    if (!checkConn()) return;
    setBusy(true);
    try {
      const ack = await deviceStartSingle();
      if (ack.result !== 0x01) Alert.alert('单次采集失败', ack.reason);
      return ack;
    } catch (e: any) {
      Alert.alert('单次采集超时', e.message);
    } finally {
      setBusy(false);
    }
  }, []);

  const stop = useCallback(async () => {
    setBusy(true);
    // Immediately stop processing buffered frames
    useDeviceStore.getState().setDeviceStatus('idle');
    flushPendingData();
    try {
      for (let attempt = 0; attempt < 3; attempt++) {
        try {
          const ack = await deviceStop();
          if (ack.result === 0x01) return;
        } catch {
          // retry
        }
      }
      Alert.alert('停止采集', '设备未确认，已强制停止');
    } finally {
      setBusy(false);
    }
  }, []);

  return {
    busy,
    connected: connStore.status === 'connected',
    status: connStore.status,
    deviceStatus: devStore.deviceStatus,
    connect,
    disconnect,
    setup,
    startContinuous,
    startSingle,
    stop,
  };
}
