import React, { createContext, useContext, useState, useCallback } from 'react';
import type { Beneficiary } from '@/types';

interface BeneficiaryContextType {
  currentBeneficiary: Beneficiary | null;
  setCurrentBeneficiary: (beneficiary: Beneficiary | null) => void;
  clearCurrentBeneficiary: () => void;
  // Helper to format beneficiary context for AI
  getBeneficiaryContext: () => string;
  // Debug: Override deployment ID for testing (used by Debug screen)
  debugDeploymentId: string | null;
  setDebugDeploymentId: (id: string | null) => void;
}

const BeneficiaryContext = createContext<BeneficiaryContextType | undefined>(undefined);

export function BeneficiaryProvider({ children }: { children: React.ReactNode }) {
  const [currentBeneficiary, setCurrentBeneficiary] = useState<Beneficiary | null>(null);
  // Debug: Override deployment ID for testing purposes
  const [debugDeploymentId, setDebugDeploymentId] = useState<string | null>(null);

  const clearCurrentBeneficiary = useCallback(() => {
    setCurrentBeneficiary(null);
  }, []);

  const getBeneficiaryContext = useCallback(() => {
    if (!currentBeneficiary) {
      return '';
    }

    const parts = [`[Context: Asking about ${currentBeneficiary.name}`];

    if (currentBeneficiary.relationship) {
      parts.push(`(${currentBeneficiary.relationship})`);
    }

    if (currentBeneficiary.sensor_data) {
      const sensor = currentBeneficiary.sensor_data;
      const sensorInfo: string[] = [];

      if (sensor.motion_detected !== undefined) {
        sensorInfo.push(`motion: ${sensor.motion_detected ? 'active' : 'inactive'}`);
      }
      if (sensor.last_motion) {
        sensorInfo.push(`last motion: ${sensor.last_motion}`);
      }
      if (sensor.door_status) {
        sensorInfo.push(`door: ${sensor.door_status}`);
      }
      if (sensor.temperature !== undefined) {
        sensorInfo.push(`temp: ${sensor.temperature}°C`);
      }
      if (sensor.humidity !== undefined) {
        sensorInfo.push(`humidity: ${sensor.humidity}%`);
      }

      if (sensorInfo.length > 0) {
        parts.push(`| Sensors: ${sensorInfo.join(', ')}`);
      }
    }

    if (currentBeneficiary.last_activity) {
      parts.push(`| Last activity: ${currentBeneficiary.last_activity}`);
    }

    parts.push(']');

    return parts.join(' ');
  }, [currentBeneficiary]);

  return (
    <BeneficiaryContext.Provider
      value={{
        currentBeneficiary,
        setCurrentBeneficiary,
        clearCurrentBeneficiary,
        getBeneficiaryContext,
        debugDeploymentId,
        setDebugDeploymentId,
      }}
    >
      {children}
    </BeneficiaryContext.Provider>
  );
}

export function useBeneficiary() {
  const context = useContext(BeneficiaryContext);
  if (context === undefined) {
    throw new Error('useBeneficiary must be used within a BeneficiaryProvider');
  }
  return context;
}
