'use client';

import { createContext, useContext, ReactNode, useState, useEffect, useRef } from 'react';
import { ProfileDetail, SystemPermission } from '@fenghuo/common';
import { useProfile as useProfileMutations, useTRPC } from '@fenghuo/client';
import { toast } from '@nice/ui/components/sonner';
import { useQuery } from '@tanstack/react-query';
import { useAuth } from '@/components/providers/auth-provider';

interface ProfileContextType {
	// 状态
	isSheetOpen: boolean;
	setIsSheetOpen: (open: boolean) => void;
	editingProfile: ProfileDetail | null;
	sheetMode: 'create' | 'edit';

	// 处理函数
	handleAddEmployee: () => void;
	handleViewDetail: (profileId: string) => void;
	handleDeleteEmployee: (profileId: string, refetch?: () => void) => void;
	handleSubmitEmployee: (formData: any) => void;

	// 注册refetch函数
	registerRefetch: (refetch: () => void) => void;
}

const ProfileContext = createContext<ProfileContextType | null>(null);

interface ProfileProviderProps {
	children: ReactNode;
}

export function ProfileProvider({ children }: ProfileProviderProps) {
	const [isSheetOpen, setIsSheetOpen] = useState(false);
	const [editingProfile, setEditingProfile] = useState<ProfileDetail | null>(null);
	const [sheetMode, setSheetMode] = useState<'create' | 'edit'>('create');
	const [selectedProfileId, setSelectedProfileId] = useState<string | null>(null);

	const { hasPermission } = useAuth();

	// 使用ref存储refetch函数
	const refetchRef = useRef<(() => void) | null>(null);

	const { create, update, softDeleteByIds } = useProfileMutations();
	const trpc = useTRPC();

	// 查询单个profile详情（用于编辑）
	const { data: profileDetail, isLoading: profileDetailLoading } = useQuery({
		...trpc.profile.findFirst.queryOptions({
			where: {
				id: selectedProfileId || '',
			},
			include: {
				organization: {
					include: {
						children: true,
						parent: true,
						terms: {
							include: {
								taxonomy: true,
							}
						}
					},
				},
			},
		}),
		enabled: !!selectedProfileId && sheetMode === 'edit',
	});

	// 当查询到profile详情时，设置编辑数据
	useEffect(() => {
		if (profileDetail && sheetMode === 'edit') {
			setEditingProfile(profileDetail);
		}
	}, [profileDetail, sheetMode]);

	const registerRefetch = (refetch: () => void) => {
		refetchRef.current = refetch;
	};

	const handleAddEmployee = () => {
		setEditingProfile(null);
		setSelectedProfileId(null);
		setSheetMode('create');
		setIsSheetOpen(true);
	};

	const handleViewDetail = (profileId: string) => {
		setSelectedProfileId(profileId);
		setSheetMode('edit');
		setIsSheetOpen(true);
	};

	const handleDeleteEmployee = (profileId: string, refetch?: () => void) => {
		if (!hasPermission(SystemPermission.PROFILE_DELETE)) {
			toast.error('您没有权限删除员工信息');
			return;
		}
		softDeleteByIds.mutate(
			{ ids: [profileId] },
			{
				onSuccess: () => {
					toast.success('员工删除成功！');
					refetch?.();
				},
				onError: (error) => {
					toast.error(`删除失败: ${error.message}`);
				},
			}
		);
	};

	const handleSubmitEmployee = (formData: any) => {
		const profileData = {
			name: formData.name,
			gender: formData.gender,
			idNum: formData.idNum,
			paperId: formData.paperId,
			avatar: formData.avatar,
			hireDate: formData.hireDate,
			birthday: formData.birthday,
			relativeHireDate: formData.relativeHireDate,
			identity: formData.identity,
			level: formData.level,
			levelDate: formData.levelDate,
			dutyCode: formData.dutyCode,
			dutyLevel: formData.dutyLevel === '' || formData.dutyLevel === undefined || formData.dutyLevel === null ? 0 : Number(formData.dutyLevel),
			dutyName: formData.dutyName,
			command: formData.command,
		};

		const profileMetadata = formData.metadata || {};

		if (sheetMode === 'create') {
			if (!hasPermission(SystemPermission.PROFILE_CREATE)) {
				toast.error('您没有权限创建员工信息');
				return;
			}
			const createData = {
				data: {
					...profileData,
					metadata: profileMetadata,
					organization: {
						connect: {
							id: formData.organizationId,
						},
					},
				},
			};
			create.mutate(createData, {
				onSuccess: (data) => {
					toast.success('员工信息保存成功！');
					setIsSheetOpen(false);
					refetchRef.current?.();
				},
				onError: (error) => {
					toast.error(`员工信息保存失败: ${error.message}`);
				},
			});
		} else if (sheetMode === 'edit' && editingProfile) {
			if (!hasPermission(SystemPermission.PROFILE_EDIT)) {
				toast.error('您没有权限更新员工信息');
				return;
			}
			const updateData = {
				where: {
					id: editingProfile.id,
				},
				data: {
					...profileData,
					metadata: profileMetadata,
					organization: {
						connect: {
							id: formData.organizationId,
						},
					},
				},
			};
			update.mutate(updateData, {
				onSuccess: (data) => {
					toast.success('员工信息更新成功！');
					setIsSheetOpen(false);
					refetchRef.current?.();
				},
				onError: (error) => {
					toast.error(`员工信息更新失败: ${error.message}`);
				},
			});
		}
	};

	const value: ProfileContextType = {
		// 状态
		isSheetOpen,
		setIsSheetOpen,
		editingProfile,
		sheetMode,

		// 处理函数
		handleAddEmployee,
		handleViewDetail,
		handleDeleteEmployee,
		handleSubmitEmployee,
		registerRefetch,
	};

	return (
		<ProfileContext.Provider value={value}>
			{children}
		</ProfileContext.Provider>
	);
}

export function useProfile() {
	const context = useContext(ProfileContext);
	if (!context) {
		throw new Error('useProfile must be used within a ProfileProvider');
	}
	return context;
}