import { useState, useCallback } from 'react';
import { invoke } from '@tauri-apps/api/core';
import {
  MaterialUsageStats,
  ProjectMaterialUsageOverview,
  MaterialUsageRecord,
  CreateMaterialUsageRecordRequest,
  UseMaterialUsageReturn
} from '../types/materialUsage';

/**
 * 素材使用状态管理的自定义Hook
 * 提供素材使用状态的数据获取和操作功能
 */
export const useMaterialUsage = (): UseMaterialUsageReturn => {
  // 状态管理
  const [usageStats, setUsageStats] = useState<MaterialUsageStats[]>([]);
  const [usageOverview, setUsageOverview] = useState<ProjectMaterialUsageOverview | null>(null);
  const [usageRecords, setUsageRecords] = useState<MaterialUsageRecord[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // 清除错误
  const clearError = useCallback(() => {
    setError(null);
  }, []);

  // 加载项目的素材使用统计
  const loadUsageStats = useCallback(async (projectId: string) => {
    try {
      setIsLoading(true);
      setError(null);
      
      const stats = await invoke<MaterialUsageStats[]>('get_project_material_usage_stats', {
        projectId
      });
      
      setUsageStats(stats);
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '获取素材使用统计失败';
      setError(errorMessage);
      console.error('加载素材使用统计失败:', err);
    } finally {
      setIsLoading(false);
    }
  }, []);

  // 加载项目的素材使用概览
  const loadUsageOverview = useCallback(async (projectId: string) => {
    try {
      setIsLoading(true);
      setError(null);
      
      const overview = await invoke<ProjectMaterialUsageOverview>('get_project_material_usage_overview', {
        projectId
      });
      
      setUsageOverview(overview);
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '获取素材使用概览失败';
      setError(errorMessage);
      console.error('加载素材使用概览失败:', err);
    } finally {
      setIsLoading(false);
    }
  }, []);

  // 加载项目的素材使用记录
  const loadUsageRecords = useCallback(async (projectId: string) => {
    try {
      setIsLoading(true);
      setError(null);
      
      const records = await invoke<MaterialUsageRecord[]>('get_project_material_usage_records', {
        projectId
      });
      
      setUsageRecords(records);
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '获取素材使用记录失败';
      setError(errorMessage);
      console.error('加载素材使用记录失败:', err);
    } finally {
      setIsLoading(false);
    }
  }, []);

  // 创建素材使用记录
  const createUsageRecord = useCallback(async (request: CreateMaterialUsageRecordRequest) => {
    try {
      setError(null);
      
      await invoke('create_material_usage_record', {
        request
      });
      
      // 创建成功后，重新加载相关数据
      if (request.project_id) {
        await Promise.all([
          loadUsageStats(request.project_id),
          loadUsageOverview(request.project_id),
          loadUsageRecords(request.project_id)
        ]);
      }
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '创建素材使用记录失败';
      setError(errorMessage);
      console.error('创建素材使用记录失败:', err);
      throw err;
    }
  }, [loadUsageStats, loadUsageOverview, loadUsageRecords]);

  // 重置素材片段使用状态
  const resetSegmentUsage = useCallback(async (segmentIds: string[]) => {
    try {
      setError(null);
      
      const result = await invoke<string>('reset_material_segment_usage', {
        segmentIds
      });
      
      console.log('重置素材片段使用状态成功:', result);
      
      // 重置成功后，需要重新加载数据
      // 注意：这里需要项目ID，但我们没有直接的方式获取
      // 在实际使用中，调用方应该手动刷新数据
      
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '重置素材片段使用状态失败';
      setError(errorMessage);
      console.error('重置素材片段使用状态失败:', err);
      throw err;
    }
  }, []);

  // 重置项目所有素材使用状态
  const resetProjectUsage = useCallback(async (projectId: string) => {
    try {
      setError(null);
      
      const result = await invoke<string>('reset_project_material_usage', {
        projectId
      });
      
      console.log('重置项目素材使用状态成功:', result);
      
      // 重置成功后，重新加载所有相关数据
      await Promise.all([
        loadUsageStats(projectId),
        loadUsageOverview(projectId),
        loadUsageRecords(projectId)
      ]);
      
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '重置项目素材使用状态失败';
      setError(errorMessage);
      console.error('重置项目素材使用状态失败:', err);
      throw err;
    }
  }, [loadUsageStats, loadUsageOverview, loadUsageRecords]);

  // 获取素材片段的使用状态
  const getSegmentUsageStatus = useCallback((segmentId: string): 'unused' | 'used' | 'multiple' => {
    const segmentRecords = usageRecords.filter(record => record.material_segment_id === segmentId);
    
    if (segmentRecords.length === 0) {
      return 'unused';
    } else if (segmentRecords.length === 1) {
      return 'used';
    } else {
      return 'multiple';
    }
  }, [usageRecords]);

  // 获取素材的使用率
  const getMaterialUsageRate = useCallback((materialId: string): number => {
    const materialStats = usageStats.find(stats => stats.material_id === materialId);
    return materialStats?.usage_rate || 0;
  }, [usageStats]);

  return {
    // 数据
    usageStats,
    usageOverview,
    usageRecords,
    
    // 状态
    isLoading,
    error,
    
    // 操作
    loadUsageStats,
    loadUsageOverview,
    loadUsageRecords,
    createUsageRecord,
    resetSegmentUsage,
    resetProjectUsage,
    
    // 工具方法
    getSegmentUsageStatus,
    getMaterialUsageRate,
    clearError
  };
};

/**
 * 简化版的Hook，只获取特定项目的使用概览
 */
export const useProjectUsageOverview = (projectId: string) => {
  const [overview, setOverview] = useState<ProjectMaterialUsageOverview | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const loadOverview = useCallback(async () => {
    if (!projectId) return;
    
    try {
      setIsLoading(true);
      setError(null);
      
      const result = await invoke<ProjectMaterialUsageOverview>('get_project_material_usage_overview', {
        projectId
      });
      
      setOverview(result);
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '获取项目使用概览失败';
      setError(errorMessage);
      console.error('加载项目使用概览失败:', err);
    } finally {
      setIsLoading(false);
    }
  }, [projectId]);

  return {
    overview,
    isLoading,
    error,
    loadOverview,
    clearError: () => setError(null)
  };
};
