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;
}

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

export function BeneficiaryProvider({ children }: { children: React.ReactNode }) {
  const [currentBeneficiary, setCurrentBeneficiary] = useState<Beneficiary | null>(null);

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

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

    const b = currentBeneficiary;
    const contextParts: string[] = [];

    // Basic info
    contextParts.push(`Person: ${b.name}`);

    if (b.address) {
      contextParts.push(`Address: ${b.address}`);
    }

    // Current status
    if (b.last_location) {
      contextParts.push(`Current location: ${b.last_location}`);
    }

    if (b.before_last_location) {
      contextParts.push(`Previous location: ${b.before_last_location}`);
    }

    // Health metrics
    if (b.wellness_score !== undefined) {
      contextParts.push(`Wellness score: ${b.wellness_score}% (${b.wellness_descriptor || 'N/A'})`);
    }

    // Temperature
    if (b.temperature !== undefined) {
      const unit = b.units || '°F';
      contextParts.push(`Room temperature: ${b.temperature.toFixed(1)}${unit}`);
    }

    if (b.bedroom_temperature !== undefined) {
      const unit = b.units || '°F';
      contextParts.push(`Bedroom temperature: ${b.bedroom_temperature.toFixed(1)}${unit}`);
    }

    // Sleep data
    if (b.sleep_hours !== undefined) {
      contextParts.push(`Sleep hours: ${b.sleep_hours.toFixed(1)} hours`);
    }

    // Activity time
    if (b.last_detected_time) {
      contextParts.push(`Last detected: ${b.last_detected_time}`);
    }

    // Status
    contextParts.push(`Status: ${b.status === 'online' ? 'Active' : 'Inactive'}`);

    return `[SENSOR DATA FOR ${b.name.toUpperCase()}: ${contextParts.join('. ')}]`;
  }, [currentBeneficiary]);

  return (
    <BeneficiaryContext.Provider
      value={{
        currentBeneficiary,
        setCurrentBeneficiary,
        clearCurrentBeneficiary,
        getBeneficiaryContext,
      }}
    >
      {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;
}
