import { useState, useEffect, useCallback } from 'react';
import { managerAgent } from '@/utils/agentClient';
import { toast } from 'sonner';

export interface Goal {
  id: string;
  title: string;
  description?: string;
  target_value: number;
  current_value: number;
  unit: string;
  deadline: string;
  priority: 'low' | 'medium' | 'high';
  status: 'active' | 'completed' | 'cancelled';
  agent_type: string;
  assigned_by?: string;
  assigned_to?: string;
  created_by?: string;
  created_at: string;
  updated_at: string;
}

export interface CreateGoalParams {
  title: string;
  description?: string;
  targetValue: number;
  currentValue?: number;
  unit?: string;
  deadline: string;
  priority?: 'low' | 'medium' | 'high';
  agentType: string;
  assignedBy?: string;
  assignedTo?: string;
}

export function useGoals(agentType?: string) {
  const [goals, setGoals] = useState<Goal[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchGoals = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      
      const params: Record<string, any> = { status: 'active' };
      if (agentType) params.agentType = agentType;
      
      const result = await managerAgent.goals.query(params);
      
      if (result.success && result.data) {
        setGoals(result.data);
      } else {
        setError(result.error || '获取目标失败');
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : '未知错误');
    } finally {
      setLoading(false);
    }
  }, [agentType]);

  useEffect(() => {
    fetchGoals();
  }, [fetchGoals]);

  const createGoal = async (params: CreateGoalParams) => {
    try {
      const result = await managerAgent.goals.create(params);
      
      if (result.success) {
        toast.success(result.message || '目标创建成功');
        await fetchGoals();
        return result.data as Goal;
      } else {
        toast.error(result.error || '目标创建失败');
        return null;
      }
    } catch (err) {
      toast.error(err instanceof Error ? err.message : '创建失败');
      return null;
    }
  };

  const updateGoal = async (id: string, params: Partial<CreateGoalParams>) => {
    try {
      const result = await managerAgent.goals.update(id, params);
      
      if (result.success) {
        toast.success(result.message || '目标更新成功');
        await fetchGoals();
        return true;
      } else {
        toast.error(result.error || '目标更新失败');
        return false;
      }
    } catch (err) {
      toast.error(err instanceof Error ? err.message : '更新失败');
      return false;
    }
  };

  const updateProgress = async (id: string, currentValue: number) => {
    try {
      const result = await managerAgent.goals.updateProgress(id, currentValue);
      
      if (result.success) {
        toast.success(result.message || '进度已更新');
        await fetchGoals();
        return true;
      } else {
        toast.error(result.error || '进度更新失败');
        return false;
      }
    } catch (err) {
      toast.error(err instanceof Error ? err.message : '更新失败');
      return false;
    }
  };

  const deleteGoal = async (id: string) => {
    try {
      const result = await managerAgent.goals.delete(id);
      
      if (result.success) {
        toast.success(result.message || '目标已删除');
        await fetchGoals();
        return true;
      } else {
        toast.error(result.error || '删除失败');
        return false;
      }
    } catch (err) {
      toast.error(err instanceof Error ? err.message : '删除失败');
      return false;
    }
  };

  // 获取当前 agent 的主要目标
  const primaryGoal = goals.find(g => g.agent_type === agentType) || goals[0];

  return {
    goals,
    primaryGoal,
    loading,
    error,
    refresh: fetchGoals,
    createGoal,
    updateGoal,
    updateProgress,
    deleteGoal
  };
}
